2 回答
TA贡献1842条经验 获得超21个赞
不幸的是,:not只接受一个简单的选择器,因此:not([required] [content])匹配[content]不是子元素的选择器[content]是行不通的。选择元素后,您必须以编程方式过滤它们:
const notRequiredContents = [...document.querySelectorAll('[content]')]
.filter(elm => !elm.closest('[required]'));
console.log(notRequiredContents);
<div>
<div required>
<div content></div>
</div>
<div>
<div content></div>
</div>
</div>
理论上可以通过:not([required])与后代选择器链接来仅使用查询字符串来完成此操作,但它看起来非常丑陋且重复,不应该这样做:
const notRequiredContents = document.querySelectorAll(`
body > :not([required]) > [content],
body > :not([required]) > :not([required]) > [content],
body > :not([required]) > :not([required]) > :not([required]) > [content],
body > :not([required]) > :not([required]) > :not([required]) > :not([required]) > [content]
`);
// continue above pattern for as much nesting as may exist
console.log(notRequiredContents[0], notRequiredContents.length);
<div>
<div required>
<div content>a</div>
</div>
<div>
<div content>b</div>
</div>
</div>
TA贡献1847条经验 获得超7个赞
JS
const query = document.querySelectorAll('div :not([required]) [content]')
query.forEach((element) => {
console.log(element.innerHTML)
})
超文本标记语言
<div>
<div required>
<div content>NO</div>
</div>
<div>
<div content>YES</div>
<div>
<div content>YES</div>
</div>
</div>
</div>
- 2 回答
- 0 关注
- 261 浏览
添加回答
举报