5

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?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
J33nn
  • 3,034
  • 5
  • 30
  • 46

3 Answers3

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>
vsync
  • 118,978
  • 58
  • 307
  • 400
1

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;

Community
  • 1
  • 1
pol
  • 2,641
  • 10
  • 16
  • Wow, didn't think of it... Like seriously man, it doesn't even partially answering my question. Ok after edit at least it contains some meaningful information. – J33nn Feb 13 '17 at 11:46
  • @pol, this is actually pretty smart. – Pacerier Apr 24 '20 at 06:08
1

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.

Community
  • 1
  • 1