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
363 views
in Technique[技术] by (71.8m points)

javascript - Is element.querySelector() different from document.querySelector()?

Looking through the mdn "querySelector" pops up under both sections and yet they both seem to achieve the same ends. Is either one ideal for different situations? ...or are they, basically, functionally the same?

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

it's more efficient to use Element.querySelector() because you're referencing to a narrower target if compared to Document.querySelector();

in both ways you'll have access to the DOM tree, but since the starting point is always document using Document.querySelector() you'll be traversing the dom entirely from the root until a child element will match.

On the other hand Element is already a reference to a certain node so the query won't begin from root, with all that comes with it ...


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

...