document.querySelector 排除部分 DOM

我的目标是在 DOM 中选择h2, h3, h4标题级别元素,除了docs-body__heading类内的元素

我试过这个:

document.querySelectorAll(`:not(.docs-body__heading) h2, h2, h4`);

不工作。那么,我如何querySelectorAll()在 DOM 上使用不包括它的某些部分?


不负相思意
浏览 570回答 4
4回答

慕森卡

最简单的方法是首先获取所有元素,然后过滤掉不需要的元素:const elems = [...document.querySelectorAll('h2,h4')]&nbsp; .filter( (elem) => !elem.matches('.docs-body__heading *') );console.log(elems);<div class="docs-body__heading">&nbsp; <h2>do not select me</h2>&nbsp; <div><h4>me neither</h4></div></div><div>&nbsp; <h2>select me</h2>&nbsp; <div><h4>and me</h4></div></div>最快的(就性能而言)可能是使用TreeWalker:const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, {&nbsp; acceptNode(elem) {&nbsp; &nbsp; return elem.matches('.docs-body__heading') ?&nbsp; &nbsp; &nbsp; NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;&nbsp; }}, true);const elems = [];while (walker.nextNode()) {&nbsp; const tagname = walker.currentNode.tagName;&nbsp; if (tagname === 'H2' || tagname === 'H4') {&nbsp; &nbsp; elems.push(walker.currentNode);&nbsp; }}console.log(elems);<div class="docs-body__heading">&nbsp; <h2>do not select me</h2>&nbsp; <div>&nbsp; &nbsp; <h4>me neither</h4>&nbsp; </div></div><div>&nbsp; <h2>select me</h2>&nbsp; <div>&nbsp; &nbsp; <h4>and me</h4>&nbsp; </div></div>但是,如果您不是在具有数百万个 DOM 节点的千米长文档中执行此操作,那么第一个版本应该足够了。

汪汪一只猫

这一行将满足您的所有需求!document.querySelectorAll("*:not(.docs-body__heading) > h1, *:not(.docs-body__heading) > h2, *:not(.docs-body__heading) > h4");更容易阅读:let not = "*:not(.docs-body__heading)";document.querySelectorAll(`${not} > h1, ${not} > h2, ${not} > h4`);使用样品:window.addEventListener('load', () => {&nbsp; &nbsp;var elems = document.querySelectorAll("*:not(.docs-body__heading) > h1, *:not(.docs-body__heading) > h2, *:not(.docs-body__heading) > h4");&nbsp; &nbsp;for(var i = 0 ; i < elems.length ; i++) {&nbsp; &nbsp; &nbsp; elems[i].style.backgroundColor = "red";&nbsp; &nbsp;}});<html>&nbsp; &nbsp; <head>Selector</head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <h1>1</h1>&nbsp; &nbsp; &nbsp; &nbsp; <h2>2</h2>&nbsp; &nbsp; &nbsp; &nbsp; <h4>3</h4>&nbsp; &nbsp; &nbsp; &nbsp; <div class="docs-body__heading">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h1>1</h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h2>2</h2>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h4>3</h4>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </body></html>

蓝山帝景

我认为只有当 h2/h4 是docs-body__headingconst x = document.querySelectorAll(":not(.docs-body__heading) > h2,h4");console.log(x);<div class="docs-body__heading">&nbsp; <h2>A</h2></div>&nbsp; <h4>B</h1>&nbsp; <h2>C</h1>

梵蒂冈之花

现在您正在排除具有docs-body__heading该类的元素,以排除其中使用的元素:document.querySelectorAll(`:not(.docs-body__heading&nbsp;>&nbsp;*)&nbsp;h2,&nbsp;h2,&nbsp;h4`);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript