Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have element.querySelector() include the root element?

Tags:

javascript

I'm in a unique situation where I need element.querySelector(selector) to test against the root element itself, and return it if it matches.

How would you do this?

Note that element.parentNode.querySelector(selector) wouldn't work for me since it would amtch against element's siblings.

like image 763
Daniel Birowsky Popeski Avatar asked Mar 24 '20 12:03

Daniel Birowsky Popeski


People also ask

How do you find the root element?

We can use the :root selector, which matches the root element of the document , with document. querySelector() in the following way to get the root element: console.

Can you use querySelector on an element?

The querySelector() method is available on the document object or any Element object.

Does querySelector return a node?

querySelector() will return the first node element found in the document based on the selector.


1 Answers

You could do

let matched = element.matches(selector) && element || element.querySelector(selector);

Tests the element first, which probably would make sense given the behavior of .querySelector().

like image 116
Pointy Avatar answered Oct 19 '22 08:10

Pointy