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.
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.
The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection.
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).
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.
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.
According to MDN, document.head
only gained support in IE 9, so using the other method as a fallback protects you from browser incompatibilities
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With