querySelectorAll() 排除属性及其子属性

我有一棵看起来像的元素树。


<div>

  <div required>

    <div content></div>

  </div>

  <div>

    <div content></div>

  </div>

</div>

如何在根 div 上执行 querySelector 来获取标记为“内容”的所有元素,而不获取任何位于具有“required”属性的父元素下方的元素?我在想类似的事情。


querySelectorAll('[content]:not([required]')


但是该查询将获取标记为内容且未标记为必需的所有元素,而不是获取标记为不低于必需元素的内容的所有元素。


哈士奇WWW
浏览 244回答 2
2回答

茅侃侃

不幸的是,:not只接受一个简单的选择器,因此:not([required] [content])匹配[content]不是子元素的选择器[content]是行不通的。选择元素后,您必须以编程方式过滤它们:const notRequiredContents = [...document.querySelectorAll('[content]')]&nbsp; .filter(elm => !elm.closest('[required]'));console.log(notRequiredContents);<div>&nbsp; <div required>&nbsp; &nbsp; <div content></div>&nbsp; </div>&nbsp; <div>&nbsp; &nbsp; <div content></div>&nbsp; </div></div>理论上可以通过:not([required])与后代选择器链接来仅使用查询字符串来完成此操作,但它看起来非常丑陋且重复,不应该这样做:const notRequiredContents = document.querySelectorAll(`&nbsp; body > :not([required]) > [content],&nbsp; body > :not([required]) > :not([required]) > [content],&nbsp; body > :not([required]) > :not([required]) > :not([required]) > [content],&nbsp; body > :not([required]) > :not([required]) > :not([required]) > :not([required]) > [content]`);// continue above pattern for as much nesting as may existconsole.log(notRequiredContents[0], notRequiredContents.length);<div>&nbsp; <div required>&nbsp; &nbsp; <div content>a</div>&nbsp; </div>&nbsp; <div>&nbsp; &nbsp; <div content>b</div>&nbsp; </div></div>

aluckdog

重复示例JSconst query = document.querySelectorAll('div :not([required]) [content]')query.forEach((element) => {&nbsp; console.log(element.innerHTML)})超文本标记语言<div>&nbsp; <div required>&nbsp; &nbsp; <div content>NO</div>&nbsp; </div>&nbsp; <div>&nbsp; &nbsp; <div content>YES</div>&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <div content>YES</div>&nbsp; &nbsp; </div>&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go