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.
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.
The querySelector() method is available on the document object or any Element object.
querySelector() will return the first node element found in the document based on the selector.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With