Javascript efficiency issue: multiple getElementById () versus getElementsByTagName () and looping result
1 answer
It all depends. How many elements with the specified IDs do you have? How many elements have the same name?
For example, if you want elements with IDs 1 and 3, and you have:
<ul>
<li id="1">1</li>
<li id="2">2</li>
<li id="3">3</li>
<!-- Followed by 10,000 more li tags -->
</ul>
you better not call getElementById()
twice. But if you want everything but ID 15, you are probably better off listing and checking for IDs.
Another alternative is to add a class to specific elements that you want to select. Then you can select by class (possibly with a JQuery class selector ) which will give you good performance throughout the round.
Be aware that Javascript performance is very different between browsers and even between browser versions . It is best to test against target browsers.
+5
source to share