Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  133] [ 1]  / answers: 1 / hits: 27334  / 12 Years ago, sat, february 23, 2013, 12:00:00

When using JavaScript in the web browser is there any performance difference between the following:



Existing getElementById



document.getElementById(elem);


Query Selector using #id



document.querySelector(#elem);


Query Selector using [id=elem]



document.querySelector([id=elem]);


I'm assuming the first one will be fastest (only has to lookup elements with an ID). Also the final one looks like bad practice. I like the second one as using querySelector for everything makes the code easy to read.



Any suggestions?


More From » html

 Answers
19

Firstly,



document.querySelector(#elem);


Has an advantage in the fact that, unlike document.getElementId, it can return classes. However, the usefulness of this is far diminished by the fact that it only returns the first object with that class name, so you might as well just use an id if you're not specifically looking for the first object with that classname. if you use,



document.querySelectorAll


However, I believe (I may be wrong), it returns all items with that classname as an array, where regular querySelector is equivalent to querySelectorAll[0]. One more advantage, is that you can run css3 queries through it, which can be quite useful.



Secondly,



document.getElementById(elem);


Has a very good advantage over queryselector in the sense that it is almost 5 times faster, so if you're sitting there with several thousand lines of code and you want to optimise said code, then getElementById is the way to go.



Lastly,



document.querySelector([id=elem]);


I, personally, don't see the need to use this in any situation. If you needed a querySelector, why not just use a # ? This is exactly equivalent to your first example of querySelector, however it has a lot of useless charaters.



Edit: Just to be clear, in summary, you're probably better off using document.getElementById.


[#80041] Friday, February 22, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiasavannahw

Total Points: 448
Total Questions: 122
Total Answers: 113

Location: Maldives
Member since Tue, Dec 21, 2021
3 Years ago
tiasavannahw questions
Sun, Oct 11, 20, 00:00, 4 Years ago
Sat, Aug 29, 20, 00:00, 4 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Mon, Mar 23, 20, 00:00, 4 Years ago
;