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

问题描述

看来我遇到了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'))

一无所获

Element接口的querySelector()方法返回第一个元素,该元素是在其上调用的与指定选择器组匹配的元素的后代。 -mdn(重点是我的

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

之所以匹配

匹配时会考虑元素的整个层次结构,包括那些在元素集之外的元素,包括baseElement及其后代;换句话说,选择器首先应用于整个文档,而不是应用于baseElement,以生成潜在元素的初始列表。然后检查结果元素是否为baseElement的后代。其余元素的第一个匹配项由querySelector()方法返回。 -mdn(重点是我):

感谢您对Evolutionxbox和G-Cyrillus的评论。