admin管理员组文章数量:1402321
Soo basically I want to select element which has specific child elements. For now I have selector which selects the child element of a chain:
const el = document.querySelector('#leftMenu ul > li > a:not(.active) + ul > li.active')
Now to get the element I'm interested in i have to do this:
const x = el.parentNode.parentNode;
Is there any way to get this element staight from the selector itself?
Soo basically I want to select element which has specific child elements. For now I have selector which selects the child element of a chain:
const el = document.querySelector('#leftMenu ul > li > a:not(.active) + ul > li.active')
Now to get the element I'm interested in i have to do this:
const x = el.parentNode.parentNode;
Is there any way to get this element staight from the selector itself?
Share Improve this question edited Feb 13, 2017 at 16:15 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Feb 13, 2017 at 11:41 J33nnJ33nn 3,2445 gold badges35 silver badges47 bronze badges 2- if you'd use jQuery syntax, it could be possible to get it in one line. – Banzay Commented Feb 13, 2017 at 11:55
- True, life would be so much easier :) But unfortunately I can't use jquery. – J33nn Commented Feb 13, 2017 at 12:10
3 Answers
Reset to default 3In Chrome 105+ you can use the :has
pseudo selector:
document.querySelector(`a:has(b)`).style.color = 'red'
<a>1</a>
<a><b>2</b></a>
<a>3</a>
Currently, there is no way to select a parent (i.e. an element with specified children). See Is there a CSS parent selector?
There may be one in the future, but currently, your method looks like the best solution.
There is no parent selector,
However it should be available in CSS level 4, which is a long way from being implemented.
So, the best thing you can do is to add in one line:
const el = document.querySelector('#leftMenu ul > li > a:not(.active) + ul > li.active').parentNode.parentNode;
本文标签: javascriptQuery selector for element having specific childStack Overflow
版权声明:本文标题:javascript - Query selector for element having specific child - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744293158a2599211.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论