Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelector vs. getElementById [closed]

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?

like image 304
goesToEleven Avatar asked Oct 19 '22 01:10

goesToEleven


People also ask

Is it better to use querySelector or getElementById?

You should opt to use the querySelector method if you need to select elements using more complex rules that are easily represented using a CSS selector. If you want to select an element by its ID, using getElementById is a good choice.

What can I use instead of querySelector?

The other alternative is element. query / queryAll . These are alternative methods to querySelector and querySelectorAll that exist on DOM parent nodes. They also take selectors, except these selectors are interpreted relative to the element being queried from.

Is querySelector better than getElementsByClassName?

querySelectorAll successfully removes the classes from all the elements, but getElementsByClassName only removes the classes from about half the elements.

Why do we use querySelector?

The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document. Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method.


2 Answers

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

like image 191
Quentin Avatar answered Oct 20 '22 15:10

Quentin


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

like image 48
Thiago Negri Avatar answered Oct 20 '22 15:10

Thiago Negri