即使querySelector(' div')不匹配,为什么querySelector(' div span')匹配? [英] Why does querySelector('div span') match even though querySelector('div') does not?

查看:68
本文介绍了即使querySelector(' div')不匹配,为什么querySelector(' div span')匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

我的浏览器:Mozilla Firefox 78.4.0esr

My browser: Mozilla Firefox 78.4.0esr

推荐答案

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

一无所获

Element接口的querySelector()方法返回第一个元素,该元素是与指定选择器组匹配的被调用元素的后代.- mdn (强调我的意思)

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

之所以匹配

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

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的评论.

Thank you evolutionxbox and G-Cyrillus for your comments.

这篇关于即使querySelector(&amp;#39; div&amp;#39;)不匹配,为什么querySelector(&amp;#39; div span&amp;#39;)匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆