Search code examples
javascriptcssdomselectors-api

Why does querySelector('div span') match even though querySelector('div') does not?


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


Solution

  • 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.