Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

javascript - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...