Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using document.getElementsByTagName() a good idea or bad idea?

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.

like image 931
Jacob Avatar asked Sep 15 '25 13:09

Jacob


1 Answers

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.

like image 120
Sanghyun Lee Avatar answered Sep 18 '25 06:09

Sanghyun Lee