Changing page colors with name

Asked

Viewed 53 times

0

I made a routine that changes all colors of the page, but only works if it is by id, for example:

document.getElementById("PriColor").style["background-color"] = "rgb(155,155,155)";

There’s a way I can do it name fields? For example:

document.getElementsByName("SecColor").style["background-color"] = "rgb(111,160,253)";

When I wear hair name, it returns the error:

Typeerror: Cannot set Property 'background-color' of Undefined

2 answers

5


This is because the function getElementsByName returns a list of DOM elements, while the function getElementById returns only one DOM element. This is also noticeable by the semantics of the method (plural and singular).

The correct code should be:

document.getElementsByName("SecColor").forEach(element => {
    element.style["background-color"] = "rgb(111,160,253)";
})  
  • Got it @Marcel, thanks for the info !!

0

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)";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.