为什么 querySelector('div span') 匹配,即使 querySelector('div') 不匹配?

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

看来我遇到了 querySelector API 的一个令人惊讶的怪癖。有人可以向我解释为什么我会得到这个结果吗?

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>

我的浏览器:Mozilla Firefox 78.4.0esr

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

没有找到因为

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'))

匹配因为

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):

感谢 evolutionxbox 和 G-Cyrillus 的评论。