javascript - Query selector for element having specific child - Stack Overflow

Soo basically I want to select element which has specific child elements. For now I have selector which

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
Add a ment  | 

3 Answers 3

Reset to default 3

In 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;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744293159a4567129.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信