tags:

views:

163

answers:

3

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?

+1  A: 

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.

Gregoire
+3  A: 

The 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 retrive anything.

Nothing to do with specific browsers.

KThompson
Keyword that got you my vote was context ;-)
Andy E
A: 

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 comes 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 become more complicated, 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.

ajm