-1
What is the meaning of this "[0]" in this JS?
const main = document.getElementsByTagName('main')[0]
-1
What is the meaning of this "[0]" in this JS?
const main = document.getElementsByTagName('main')[0]
4
Hello
You are using the getelementsbytagname method that searches for all elements whose tag matches the one entered in the parameter. This method should return an array of elements.
More details of this method: https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
When returning an array you need to access each element of through its index (which resembles the home address of the element in that list). This is done using brackets and between them the position index of the desired element.
NOTE: remembering that the indexes in arrays start from 0.
In its specific case it is storing in the variable the first element with main tag of the document.
In short: [0] means the first element of the list.
Thanks .
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.