在这个jQuery选择器中有什么香草JS相当于?
final KStream<String, String> inputStream = builder.stream("inputStream");
...
inputStream
.filter(this::acceptCertainMessages)
.transform(new MyTransformerSupplier<String, String>("store"), "store")
.to("outputStream");
在$('.main-container').children('.analytics:has(a)').not('#promo')
内,我正在尝试选择所有.main-container
个元素,而不包含包含.analytics
标记的“promo”ID。
我尝试了什么:
<a>
这会让我接近我想要的内容,但我仍然需要过滤掉不拥有document.querySelectorAll('.main-container .analytics:not(#promo)')
代码的.analytics
个父母。
使用vanilla JS解决这个问题的最佳方式是什么?
答案 0 :(得分:4)
.analytics:not(#promo)
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.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>
答案 1 :(得分:1)
您可以选择<a>
,然后获取其父节点:
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>
是您想要的元素的直接子项时才有效。
答案 2 :(得分:1)
: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.