Reputation: 3234
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
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
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
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