[英]In vanilla JS, how do I use querySelectorAll with 2 pseudo-selectors?
I'm re-writing some jQuery as vanilla JS - it looks like this: 我正在将一些jQuery重新编写为原始JS-看起来像这样:
$('.main-container').children('.module:has(a)').not('#promo');
What I've tried: 我尝试过的
document.querySelectorAll('.main-container .module:has(a):not(#promo)');
But using two pseudo-selectors in one statement is what's throwing me off. 但是,在一个语句中使用两个伪选择器真是令人讨厌。 Using only the :not(#promo)
selector works as it should: 仅使用:not(#promo)
选择器可以正常工作:
document.querySelectorAll('.main-container .module:not(#promo)');
But things fall apart when I try adding :has(a)
. 但是当我尝试添加:has(a)
时,事情就崩溃:has(a)
。 What am I missing? 我想念什么?
Rearrange your selector like so: 重新排列选择器,如下所示:
var modules = document.querySelectorAll('.main .module:not(#exclude)');
Then filter()
for .module
s that .contains(a)
然后filter()
为.module
s表示.contains(a)
See demo and let me know if the HTML is correct or not since it's not posted 观看演示,让我知道HTML是否正确(因为未发布)
Index 2, 5, and 9 should be excluded 索引2、5和9应该排除在外
var modules = Array.from(document.querySelectorAll('.main .module:not(#exclude)')); var hasA = modules.filter(function(module, index, hasA) { let a = module.querySelector('a'); return module.contains(a); }); hasA.map(function(module, index, hasA) { module.insertAdjacentText('beforeend', ' INCLUDED'); return console.log(`module ${index}: ${module.textContent}`); });
.as-console-wrapper { width: 60%; margin-left: 40%; min-height: 100%; }
<ol class='main' start='0'> <li class='module'><a href='#/'>LINK</a></li> <li class='module'><a href='#/'>LINK</a></li> <li id='exclude' class='module'> <a href='#/'>LINK</a> </li> <li class='module'><a href='#/'>LINK</a></li> <li class='module'><a href='#/'>LINK</a></li> <li class='component'> <a href='#/'>LINK</a> </li> <li class='module'><a href='#/'>LINK</a></li> <li class='module'><a href='#/'>LINK</a></li> <li id='include' class='module'> <a href='#/'>LINK</a> </li> <li class='module'>NO LINK</li> </ol>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.