3

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
  • 665,005
  • 155
  • 1,345
  • 1,328
J33nn
  • 2,964
  • 5
  • 26
  • 44

2 Answers2

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,561
  • 8
  • 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