admin 管理员组

文章数量: 1086019

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.

Share Improve this question asked Mar 24, 2020 at 12:50 Daniel Birowsky PopeskiDaniel Birowsky Popeski 9,30614 gold badges71 silver badges138 bronze badges 2
  • @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
Add a ment  | 

1 Answer 1

Reset to default 12

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

本文标签: javascriptHow to have elementquerySelector() include the root elementStack Overflow