J33nn
J33nn

Reputation: 3234

Query selector for element having specific child

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?

Upvotes: 5

Views: 4398

Answers (3)

vsync
vsync

Reputation: 130065

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>

Upvotes: 3

pol
pol

Reputation: 2701

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;

Upvotes: 1

Soma De&#225;ki
Soma De&#225;ki

Reputation: 11

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.

Upvotes: 1

Related Questions