I was wondering if it would be more efficient to use document.getElementById() n number of times or to use document.getElementsByTagName() and loop through the result looking for the specific Element ids?
I was wondering if it would be more efficient to use document.getElementById() n number
Share
It all depends. How many elements with given IDs do you have? How many elements with the same tag name?
For example if you want elements with IDs 1 and 3 and you have:
you would be better off calling
getElementById()twice. But if you want everything except ID 15, you would probably be better off doing the list and checking IDs.Another alternative is to add a class to the specific elements that you want to select. Then you can select by class (perhaps with the JQuery class selector) which will give you good performance all round.
Keep in mind that Javascript performance vary wildly between browsers and even between versions of browsers. Best to do some testing against your target browsers.