Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using querySelector instead of document.getElementById [closed]

Tags:

javascript

should I replace document.getElementById or so by document.querySelector? any difference?

Will you recommend me to use querySelector?

like image 900
user2947116 Avatar asked Sep 16 '25 10:09

user2947116


1 Answers

When you are selecting on ids anyway, use getElementById as that’s a lot more efficient than using querySelector on an id selector. The latter runs the whole CSS selector parsing, while the former can just take the ID and get the element with that ID directly.

Of course, when selecting based on other criteria than the element’s id, querySelector (and querySelectorAll) obviously has its place.

(The obligatory benchmark to prove this claim, although I do want to note that benchmarks are not everything, and the difference probably won’t make much difference in an actual application.)

like image 119
poke Avatar answered Sep 19 '25 04:09

poke