最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to have element.querySelector() include the root element? - Stack Overflow

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论