1

It appears I have encountered a surprising quirk of the querySelector API. Can someone explain to me why I get this result?

const p = document.getElementById('parent')

// This line finds the span element
console.log(p.querySelector('div span'))

// Even though this line finds nothing
console.log(p.querySelector('div'))
<div id=parent>
  <span>test</span>
</div>

My browser: Mozilla Firefox 78.4.0esr

  • There is no descendant `div` of `#parent`. `querySelector`. https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector explains why the first selector works. _"The example demonstrates that the hierarchy of the entire document is considered when applying selectors, so that levels outside the specified baseElement are still considered when locating matches. - Notice how the "div span" selector still successfully matches the element, even though the baseElement's child nodes do not include the div element (it is still part of the specified selector)."_ – evolutionxbox Oct 25 '20 at 11:08
  • `p` is the div itself ... – G-Cyrillus Oct 25 '20 at 11:10
  • Related: [queryselectorAll with descendant not selecting correctly](https://stackoverflow.com/q/49545252/4642212). – Sebastian Simon Apr 11 '21 at 13:21

1 Answers1

1
console.log(p.querySelector('div'))

Finds nothing because

The querySelector() method of the Element interface returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors. -- mdn (emphasis mine)

console.log(p.querySelector('div span'))

Matches because

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. The first match of those remaining elements is returned by the querySelector() method. -- mdn (emphasis mine):

Thank you evolutionxbox and G-Cyrillus for your comments.