0

I know from here that

The entire hierarchy of elements is considered when matching, including those outside the set of elements including baseElement and its descendants; in other words, selectors is first applied to the whole document, not the baseElement, to generate an initial list of potential elements. The resulting elements are then examined to see if they are descendants of baseElement.

I do not want to consider entire hierarchy, I want to consider only descendants of my baseElement. How can I do that? Thank you.

Yaroslav Trofimov
  • 313
  • 2
  • 4
  • 16
  • 3
    `baseElement.querySelector()`? – Scott Marcus Oct 23 '18 at 20:38
  • From the very top of that same link you posted: *Returns the first element **that is a descendant of the element on which it is invoked** that matches the specified group of selectors.* While the initial set of ***potential*** matches is constructed from the entire document, the final result will only ever be from the element that `querySelector()` was called on. – Scott Marcus Oct 23 '18 at 20:39
  • This only makes a difference if the selector uses pseudo-classes like `:first`, `:last-of-type`, etc. These modifiers are applied relative to the document, not just within the specified element. – Barmar Oct 23 '18 at 21:04
  • After reading the entire page you linked I think that your interpretation is correct. The Examples section in particular shows that the whole document will be parsed and why. I think you could get around it by copying your desired baseElement into a documentFragement then using that as your baseElement. But that means you have to insert the copy into the original document to replace the original if you wanted to make changes. – frederickf Oct 23 '18 at 22:01
  • @ScottMarcus, I am asking about the consideration of descendants only instead of the whole hierarchy. `baseElement.querySelector()` considers the whole hierarchy. Hence, the `baseElement.querySelector()` is not appropriate. – Yaroslav Trofimov Oct 23 '18 at 22:36
  • I am concerned here mostly about the performance. Why should I consider the whole document, while I am interested only in part of it. – Yaroslav Trofimov Oct 23 '18 at 22:38
  • I understand what you are asking. This is how `.querySelector()` works. Technically speaking, you can't parse just a portion of the DOM document without looking at the whole thing first. Otherwise, you couldn't know that you were starting at the correct point. The performance impact is negligible. Modern CSS selector engines are very optimized for performance. – Scott Marcus Oct 23 '18 at 23:56
  • @Barmar: :last-of-type isn't applied relative to the document, and :first is part of jQuery, not the standard. – BoltClock Oct 24 '18 at 04:59

0 Answers0