Dear experts, I am quite new to javascript and I often see coders use those lines interchangeabaly.
document.body.getElementsByTagName();
and
document.getElementsByTagName();
What is the difference, benefits?
Does this have anything to do with FF and IE?
Dear experts, I am quite new to javascript and I often see coders use those lines interchangeabaly.
document.body.getElementsByTagName();
and
document.getElementsByTagName();
What is the difference, benefits?
Does this have anything to do with FF and IE?
Share Improve this question asked Mar 19, 2010 at 19:38 Dennis DDennis D 1,3434 gold badges17 silver badges24 bronze badges4 Answers
Reset to default 8The difference is the context. In the first example you're looking inside the body tag which means you can never retrieve the body tag itself or any other elements outside of that
In the second example example you can retrieve anything.
Nothing to do with specific browsers.
The first will only sort you the body elements, ie: not the head one if your document is well formed. The second will sort you all the elements that are present either in the head either in the body.
As mentioned above, the difference is context.
The first line will search for all elements of a given tag name occurring inside of the body tag.
The second line searches for all elements of a given tag name occurring inside of the entire document.
With context es speed: if you can make your search as narrow as possible, you will find your elements faster and your application will perform better.
As your documents bee more plicated, you will notice that something like this:
document.getElementById('foo').getElementsByTagName('span')
will start to perform noticeably faster than a plain old
document.getElementsByTagName('div')
Plus, in narrowing scope you will have less results, which means less iteration through DOM nodes looking for the ones upon which you wish to operate.
http://jsperf./document-body-getelementsbytagname1 tells ajm is wrong,
document.getElementsByTagName('*');
runs faster on FF!