将查询代码转换为普通javascript

Jquery code to vanilla javascript

本文关键字:javascript 转换 查询 代码      更新时间:2023-09-26

是否可以使用纯javascript实现以下内容?

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

您真的想获得一个包含所有选择器的集合,看看它是否为空。

在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')) {

请参阅document.querySelector的MDN文档。

是的!!我建议使用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
}

您可以使用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
}