Javascript querySelector 与 getElementById

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26848289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:26:27  来源:igfitidea点击:

Javascript querySelector vs. getElementById

javascriptjquerydom

提问by goesToEleven

I have heard that querySelector& querySelectorAllare new methods to select DOMelements. How do they compare to the older methods, getElementById& getElementsByClassNamein terms of performance and browser support?

我听说querySelector&querySelectorAll是选择DOM元素的新方法。他们如何比较的老方法,getElementByIdgetElementsByClassName在性能和浏览器支持方面?

How does the performance compare to using jQuery's query selector?

与使用 jQuery 的查询选择器相比,性能如何?

Is there a best practice recommendation for which native set to use?

是否有关于使用哪个本机集的最佳实践建议?

回答by Quentin

"Better" is subjective.

“更好”是主观的。

querySelectoris the newer feature.

querySelector是较新的功能。

getElementByIdis better supported than querySelector.

getElementById比 更好地支持querySelector

querySelectoris better supported than getElementsByClassName.

querySelector比 更好地支持getElementsByClassName

querySelectorlets you find elements with rules that can't be expressed with getElementByIdand getElementsByClassName

querySelector可以让你找到规则无法用getElementById和表达的元素getElementsByClassName

You need to pick the appropriate tool for any given task.

您需要为任何给定的任务选择合适的工具。

(In the above, for querySelectorread querySelector/ querySelectorAll).

(在上面,对于querySelectorread querySelector/ querySelectorAll)。

回答by Thiago Negri

The functions getElementByIdand getElementsByClassNameare very specific, while querySelectorand querySelectorAllare more elaborate. My guess is that they will actually have a worse performance.

功能getElementByIdgetElementsByClassName非常具体,而querySelectorquerySelectorAll更精细。我的猜测是他们实际上会有更糟糕的表现。

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

此外,您需要检查您所针对的浏览器中每个功能的支持情况。它越新,缺乏支持或功能“有问题”的可能性就越大。