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

本文标签: javascriptQuery selector for element having specific childStack Overflow