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

dom - Javascript Expression "document.body.getElementsByTagName();" Vs "document.getElementsByTagName

programmeradmin0浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 8

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 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!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论