最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is using document.getElementsByTagName() a good idea or bad idea? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Aug 5, 2011 at 17:02 JacobJacob 3,9658 gold badges26 silver badges25 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Absolutely the getElementById is better in that case. It's much faster.

Update

Here is a test about JavaScript selector functions. http://jsperf./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.

They do pletely 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.

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.

发布评论

评论列表(0)

  1. 暂无评论