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

Viewed 505

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.

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().

Related