2014-10-11 100 views
0

是否有無論如何實現以下使用純JavaScript?jquery代碼到香草javascript

if (! $('body.posts.show').length && ! $('body.posts.edit').length && ! $('body.chunks.create').length) 
{ 
    // Something here 
} 
+0

值得指出的:你的選擇可能比他們應該/需要更具體。 – 2014-12-26 02:16:49

回答

3

你真的想得到一個與所有這些選擇器的集合,看看它是否是空的。

在jQuery中,你可以這樣做:

if (! $('body.posts.show, body.posts.edit, body.chunks.create').length) 

香草的Javascript方法並不困難得多:

if (!document.querySelector('body.posts.show, body.posts.edit, body.chunks.create')) { 

MDN documentation for document.querySelector

+0

什麼是瀏覽器支持 – Anam 2014-10-11 07:25:33

+0

@Anam請參閱我鏈接的頁面底部。它適用於任何版本的Chrome,FF 3.5+,IE 8+。如果你需要支持IE <8,我建議你使用一個庫來幫助你。 jQuery,也許! – lonesomeday 2014-10-11 07:26:53

+0

@Anam在這裏檢查[瀏覽器支持](http://caniuse.com/#feat=queryselector) – Praveen 2014-10-11 07:27:34

1

是的!我會建議去querySelectorquerySelectorAll方法。

var body = document.querySelector('body'); 
var posts = body.querySelector('posts'); 
var chunks = body.querySelector('chunks'); 
var show = posts.querySelectorAll('show'); 
var edits = posts.querySelectorAll('edit'); 
var create = chunks..querySelectorAll('create'); 

if (!show.length && !edit.length && !create.length) { 
// Something here 
} 
1

您可以使用Javascript document.querySelectorAll('')!試試這個

if (!document.querySelectorAll('body.posts.show').length && !document.querySelectorAll('body.posts.edit').length && !document.querySelectorAll('body.chunks.create').length) 
{ 
    // Something here 
} 

更妙的是

if (!document.querySelectorAll('body.posts.show, body.posts.edit, body.chunks.create').length) 
{ 
    // Something here 
}