Is element.querySelector() different from document.querySelector()?

前端 未结 2 1891
[愿得一人]
[愿得一人] 2020-12-12 01:33

Looking through the mdn \"querySelector\" pops up under both sections and yet they both seem to achieve the same ends. Is either one ideal for different situations? ...or ar

相关标签:
2条回答
  • 2020-12-12 01:39

    it's more efficient to use Element.querySelector() because you're referencing to a narrower target if compared to Document.querySelector();

    in both ways you'll have access to the DOM tree, but since the starting point is always document using Document.querySelector() you'll be traversing the dom entirely from the root until a child element will match.

    On the other hand Element is already a reference to a certain node so the query won't begin from root, with all that comes with it ...

    0 讨论(0)
  • 2020-12-12 01:54

    The only difference is where the query is rooted. element.querySelector only searches the children of element. Because the scope is narrower it's more efficient.

    0 讨论(0)
提交回复
热议问题