-1

I made a page where the user could change the page's body/header/footer's background color by inputting the color into a textbox. My functions are:

function changebody(){
   let color = document.getElementById("bodycolor").value;
   document.body.style.backgroundColor = color;
}

function changenav(){
   let color = document.getElementById("navcolor").value;
  document.getElementsByTagName("nav").style.backgroundColor=color;
}

function changefoot(){
   let color = document.getElementById("footcolor").value;
   document.getElementsByTagName("footer").style.backgroundColor = color;
}

The function for the body works fine but i can't seem to get the function for footer and nav bar to work. Any suggestions why? (I've already checked to see if i got the right id's.)

edit: thank u for the comments!! it works now :D

kriloots
  • 69
  • 9
  • Does this answer your question? [Change style of all elements using getElementsByTagName()](https://stackoverflow.com/questions/17349081/change-style-of-all-elements-using-getelementsbytagname) – CBroe Jun 08 '20 at 07:53

2 Answers2

1

You almost got it, please change these lines:

document.getElementsByTagName("nav")[0].style.backgroundColor=color;
document.getElementsByTagName("footer")[0].style.backgroundColor = color;

The reason for this, is that getElementsByTagName() return value is like an array.

csba
  • 720
  • 8
  • 20
1

I hope you're doing good.

So, The getElementsByTagName() method accepts a tag name and returns a live HTMLCollection of elements with the matching tag name in the order in which they appear in the document. The HTMLCollection is an array-like object.

Now, in this case, there will only be one element i.e. the first one with index 0.

therefore, you must use these lines:

document.getElementsByTagName("nav")[0].style.backgroundColor=color;
document.getElementsByTagName("footer")[0].style.backgroundColor = color;