querySelector vs. getElementById

JavascriptJqueryDom

Javascript Problem Overview


I have heard that querySelector and querySelectorAll are new methods to select DOM elements. How do they compare to the older methods, getElementById and 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 method to use?

Javascript Solutions


Solution 1 - Javascript

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName but querySelector gives you a static node list while getElementsByClassName gives you a live node list.

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

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongoesToElevenView Question on Stackoverflow
Solution 1 - JavascriptQuentinView Answer on Stackoverflow
Solution 2 - JavascriptThiago NegriView Answer on Stackoverflow