简体   繁体   English

如何 select 所有与 baseElement 相关的子项(特定类型)?

[英]How to select all childs(of specific type) related to baseElement?

Let's say my code looks like that假设我的代码看起来像这样

 const menu = document.querySelector(".menu"); //now i need to select <a> tags with 'design' and 'development', but using menu element i've already selected. //const firstLineChilds = menu.querySelector(???);
 <ul class="menu"> <li><a href="#">Design</a></li> <li><a href="#">Development</a></li> <li> <ul class="sub-menu"> <li><a href="#">DevOps</a></li> <li><a href="#">Managment</a></li> </ul> </li> </ul>

Is it even possible to to this the 'clean way'?甚至有可能以“干净的方式”做到这一点吗? Or i just need to use menu.parentNode.querySelector(".menu > li > a")或者我只需要使用 menu.parentNode.querySelector(".menu > li > a")

You can chain querySelector and other such methods and it will search children of previous returned node: document.querySelector(".menu").querySelectorAll("a") or menu.querySelectorAll("a")您可以链接 querySelector 和其他此类方法,它将搜索先前返回节点的子节点: document.querySelector(".menu").querySelectorAll("a")menu.querySelectorAll("a")

Converting the hrefs to an Array (in the snippet the spread syntax is used for that) enables you to filter them:将 href 转换为Array (在代码段中使用了扩展语法),您可以过滤它们:

 const relevantHrefs = [...document.querySelectorAll(".menu li a")].filter(href => ["Design", "Development"].find(h => href.textContent === h)); console.log(relevantHrefs); // based on comment, this is maybe what OP needs const menu = [...document.querySelectorAll(".menu > li:nth-child(-n+2) a")]; console.log(menu);
 <ul class="menu"> <li><a href="#">Design</a></li> <li><a href="#">Development</a></li> <li> <ul class="sub-menu"> <li><a href="#">DevOps</a></li> <li><a href="#">Managment</a></li> </ul> </li> </ul>

Yes, you can use :scope in conjunction with child combinators, in menu.querySelectorAll() :是的,您可以在menu.querySelectorAll() :scope与子组合器一起使用:

 const menu = document.querySelector(".menu") const firstLineChilds = menu.querySelectorAll(":scope > li > a"); console.log(firstLineChilds);
 <ul class="menu"> <li><a href="#">Design</a></li> <li><a href="#">Development</a></li> <li> <ul class="sub-menu"> <li><a href="#">DevOps</a></li> <li><a href="#">Managment</a></li> </ul> </li> </ul>

If you use descendant combinators, you'll still get the nested a elements, which is not what you want.如果您使用后代组合器,您仍然会得到嵌套a元素,这不是您想要的。 See What does the ">" (greater-than sign) CSS selector mean?请参阅“>”(大于号)CSS 选择器是什么意思?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM