问题
I am learning JavaScript from the MDN web docs. I was studying Element.querySelector()
method.
It is written that it returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors.
But there is an example given, which contradicts this fact.
var baseElement = document.querySelector("p");
document.getElementById("output").innerHTML =
(baseElement.querySelector("div span").innerHTML);
<div>
<h5>Original content</h5>
<p>
inside paragraph
<span>inside span</span>
inside paragraph
</p>
</div>
<div>
<h5>Output</h5>
<div id="output"></div>
</div>
Here, div
tag is not a descendant of p
tag, still this code works.
Can you point where I am going wrong ?
回答1:
Element.querySelector()
first applies the CSS Selectors passed to .querySelector()
method, on the whole document and not the base element on which .querySelector()
was invoked. This is done to generate initial set of potential elements.
After generating initial set of potential elements, list of potential elements is then filtered to retain only those elements which are descendants of the base element. Finally, the first element from this filtered list is returned.
In your code example, entire document is first searched for elements that match div span
. As there is only one element in the entire document that matches div span
selector, initial set of potential elements contains only one span
element. After that, this span
element is checked to see if it is the descendant of baseElement
. Since, in this case, it is a descendant of
the baseElement
, it is returned.
What i explained above is written under "Return Value" heading in MDN - Element.querySelector()
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.
来源:https://stackoverflow.com/questions/62873962/in-mdn-web-docs-element-queryselector-method-says-that-it-should-be-descendant-b