Reputation: 3965
Ok so I am wondering which way is the preffered way to access a certain tag.
Is it better to use..
document.getElementById('myDiv').innerHTML
or this way..
document.getElementsByTagName('div')[0].innerHTML
// I use [0] because it is the first div in the body
My guess is that it doesn't matter at all which way i do it.
Upvotes: 4
Views: 1773
Reputation: 23002
Absolutely the getElementById
is better in that case. It's much faster.
Update
Here is a test about JavaScript selector functions. http://jsperf.com/queryselectorall-vs-getelementbyid/6
There are not many articles about performance of JavaScript selector functions. Instead there are many articles about jQuery selector performance like this or this. jQuery uses native JavaScript selector functions internally, so you can guess from these articles.
Upvotes: 5
Reputation: 6259
For readability purposes, it depends on what you're trying to do.
Is your intent to get the first div, which just happens to be named myDiv
? if yes, then I think getElementsByTagName
is better, as it would more express what you're trying to do.
Or is your intent to get myDiv
, which just happens to be the first div? If that's the case, then use getElementById
.
All other considerations aside, go with the one that expresses your intent.
Upvotes: 1
Reputation: 159915
They do completely different things. If you want to get a particular element and you always need to get the same element, use an id. If you want to get a particular element based on what place it has in the DOM, then use the it's position in the getElementsByTagName NodeList.
If you want to get a particular element and you get it by index, then your script will be brittle - if you change your DOM structure later, you will need to change your code. If you want to get an element by it's position, then using an ID will require you to add redundant attributes to your markup.
Also, it is important to note that getElementById
returns a DOM node, while getElementsByTagName
returns a NodeList. To quote MDC on the properties of a NodeList:
NodeList is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName again.
So if you need a particular element, getElementById
will be significantly faster.
Upvotes: 1