Why do getElementsByTagName() always returns an array?

Why is it that if I have only one h1 element in the document, I still have to use the index to access it?

Like the following doesn't work.

document.getElementsByTagName('h1').innerHTML = "SHUSHAN";

but if I do

document.getElementsByTagName('h1')[0].innerHTML = "SHUSHAN";

It does work.

Even though I only have one h1, why do I have to specify?

Answers:

Answer

Short answer: This is so that you can have some sanity.

If you don't know whether you will get a single element or a collection of elements, you would have to write defensive, type-checking (stupid) code like this

let foo = document.getElementsByTagName('h1')
if (foo instanceof HTMLCollection)
  // do something with all elements
else
  // do something with just one element

It makes way more sense for the function to always return a known type, an HTMLCollection of HTMLElement objects


If you only care about getting the first element, you can use destructuring assignment

let [first] = document.getElementsByTagName('h1')
console.log(first) // outputs just the first h1

This is fine because the assignment clearly shows that it's expecting an array (or array-like) of elements but only cares about assigning an identifier to the first value


You should also be aware of the newer document.querySelector and document.querySelectorAll functions …

  • document.querySelector will select at most one element from the document or returnnull

  • document.querySelectorAll will always return an HTMLCollection, but may be empty if no elements match the selector.


Here's how I'd write your code in 2017

setTimeout($ => {
  // get the element to change
  let elem = document.querySelector('h1')
  // update the text of the element
  elem.textContent = 'SHUSHAN'
}, 3000)
<h1>wait 3 seconds ...</h1>

Answer

getElementsByTagName - the method name itself implies that it will return multiple elements - i.e. an array. The method always returns an array, with the length equal to the number of matching elements. As such you must always access the elements by the index of the element in the array.

Answer

Arrays must be accessed by index regardless of how many values it holds. Do some reading on array data types to get a better understanding of the concept.

Answer

The point is that getElementsByTagName always returns a HTMLCollection of elements, which works mostly as an array. If there is only one element in this collection, then its index is 0.

This is the reason why you must specify the index, even if there is only one element in the document.

Click here or here to see more documentation about this.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.