As a id
should be unique on the page, so the function getElementById
is in the singular, because you will only select a single element.
Already the function getElementsByName
, which is plural (singular does not exist), suggests that you will select a list of nodes (nodelist) which is the collection of the value specified in the function (as well as getElementsByTagName
and getElementsByClassName
).
Unlike the id
, the name
, class
and tag
may have 1 or more occurrences on the page, and thus the function getElementsByName
will create an object nodelist with all the elements that have the name
specified, creating an array with the elements. To access these elements you need to specify an index, starting from the 0
:
document.getElementsByName("SecColor") // todos os elementos (nodelist)
document.getElementsByName("SecColor")[0] // 1º elemento
document.getElementsByName("SecColor")[1] // 2º elemento
document.getElementsByName("SecColor")[2] // 3º elemento
etc..
To change all elements of the nodelist, you must make a loop going through each of the elements, as suggested by Marcel’s reply. However, I will leave a more compatible suggestion using the for
traditional (the forEach
does not work in Microsoft browsers):
for(var x = 0; x < document.getElementsByName("SecColor").length; x++){
els[x].style.backgroundColor = "rgb(111,160,253)";
}
Got it @Marcel, thanks for the info !!
– Sora