Javascript querySelector vs. getElementById [closed]

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

I have heard that querySelector & querySelectorAll are new methods to select DOM elements. How do they compare to the older methods, getElementById & getElementsByClassName in terms of performance and browser support?

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

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

回答1:

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

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

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



回答2:

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

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".



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!