Jquery代码到vanilla javascript

时间:2014-10-11 07:15:32

标签: javascript jquery

无论如何使用纯javascript实现以下内容?

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

3 个答案:

答案 0 :(得分:3)

你真的希望得到一个包含所有选择器的单个集合,看看它是否为空。

在jQuery中,你会这样做:

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

vanilla Javascript方法并不困难:

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

请参阅MDN documentation for document.querySelector

答案 1 :(得分: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
}

答案 2 :(得分: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
}