Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.head v. document.getElementsByTagName("head")[0]

Tags:

javascript

dom

What is the difference between using document.head and using document.getElementsByTagName("head")[0]? Tests I ran showed that they both take about a millisecond.

I have also seen

document.head||document.getElementsByTagName("head")[0];

which would have led me to believe that document.head is faster and the other is more more compatible, except that the tests I did disproved this.

And if one is more compatible, why use the other as well?

Update: My tests were wrong, as some have pointed out.

like image 573
Brian McCutchon Avatar asked Apr 25 '13 01:04

Brian McCutchon


People also ask

What does document getElementsByTagName do?

getElementsByTagName() The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node.

What is getElementsByTagName in Javascript?

The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection.

Why getElementsByTagName is not working?

The "getElementsByTagName is not a function" error occurs for multiple reasons: calling the getElementsByTagName() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. misspelling getElementsByTagName (it's case sensitive).

What does getElementsByTagName return?

getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically.


2 Answers

Using the || operator like that is a form of feature detection. When used, if the first value is undefined it sends back the latter value.

So for

document.head || document.getElementsByTagName("head")[0];

the reason is that if document.head is not supported at least the right value is returned.

As for your speed test, a millisecond is a long time. I doubt it really took that long. In fact, I made a jsPerf for this. It shows that the getElementsByTagName function is roughly 80% slower.

like image 79
Travis J Avatar answered Sep 21 '22 13:09

Travis J


According to MDN, document.head only gained support in IE 9, so using the other method as a fallback protects you from browser incompatibilities

like image 22
Alex.Bullard Avatar answered Sep 20 '22 13:09

Alex.Bullard