繁体   English   中英

是否有相当于 jQuery .has() 的 vanilla JS?

[英]Is there a vanilla JS equivalent of jQuery .has()?

在这个 jQuery 选择器中,相当于 :has 的 vanilla JS 是什么?

$('.main-container').children('.analytics:has(a)').not('#promo')

.main-container ,我试图选择所有.analytics元素而没有包含<a>标签的“promo”ID。

我试过的:

document.querySelectorAll('.main-container .analytics:not(#promo)')

这将使我接近我想要的,但我仍然必须过滤掉那些没有<a>标签的.analytics父级。

使用 vanilla JS 解决这个问题的最佳方法是什么?

  1. 查询文档以使用所需的选择器,在这种情况下: .analytics:not(#promo)
  2. 将NodeList转换为数组
  3. 使用谓词过滤数组: element => element.querySelector('your-selector')

如果没有找到子元素, element.querySelector('your-selector')将计算为null (这是假的)

一般作为一种功能

 function has(nodeList, selector) { return Array.from(nodeList).filter(e => e.querySelector(selector)) } const nodeList = document.querySelectorAll('.main-container > .analytics:not(#promo)') has(nodeList, 'a').forEach(e => e.style.background = "red") 
 <div class="main-container"> <div class="analytics"> <a>Should be red</a> </div> <div class="analytics"> Should not be red </div> <div id="promo" class="analytics"> <a>Should not be red</a> </div> </div> 

作为NodeList.prototype

 NodeList.prototype.has = function(selector) { return Array.from(this).filter(e => e.querySelector(selector)) } document .querySelectorAll('.main-container > .analytics:not(#promo)') .has('a') .forEach(e => e.style.background = 'red') 
 <div class="main-container"> <div class="analytics"> <a>Should be red</a> </div> <div class="analytics"> Should not be red </div> <div id="promo" class="analytics"> <a>Should not be red</a> </div> </div> 

您可以选择<a>然后获取其parentNodes:

 var a = document.querySelectorAll('.main-container .analytics:not(#promo) a'); var yourElements = []; for (var i = 0; i < a.length; i++) { yourElements.push(a[i].parentNode); } yourElements.forEach(e => e.style.background = "red"); 
 <div class="main-container"> <div class="analytics"> <a>Should be red</a> </div> <div class="analytics"> Should not be red </div> <div id="promo" class="analytics"> <a>Schould not be red</a> </div> </div> 

编辑:只是注意到这只有在<a>是你想要的元素的直接孩子时才有效。

没有等效的选择器:has ,你必须使用初始选择,然后过滤它们

var el = document.querySelectorAll('.main-container > .analytics:not(#promo)');
var res = [];
for (let x = 0; x < el.length; x++){
    if (el[x].querySelector('a')) res.push(el[x]);
}
//res has has the array of elements needed.

Josh Larson 的 polyfill-css-has提供了一个基于普通 JavaScript 的querySelectorAllWithHas方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM