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.
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.
-
@Teemu
.closest()
goes up. – Pointy Commented Mar 24, 2020 at 12:54 -
@Teemu but if
.querySelector()
does find a match, then from that point.closest()
will I think return that found element itself, if.closest()
in the DOM API works like jQuery's. – Pointy Commented Mar 24, 2020 at 13:16
1 Answer
Reset to default 12You 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()
.