Question

What I have is

<script>
function myFunction()
{
document.getElementById("post").style.backgroundColor="#ECF6A4";
}
</script>
<button onclick="myFunction()">Change Post Color</button>

In the page there are multiple divs with the id="post" but when I save the code and try it out it only changes the background of the first div on the page with the id="post" and not any of the others.

I tried getElementsById with no luck, thats all I could think of.

Any simple fixes for this?

Was it helpful?

Solution 2

You should use class instead of id when you want to reference multiple elements.

document.getElementsByClassName('class').style.backgroundColor = "#ECF6A4"

OTHER TIPS

Multiple divs with the same id on the same page is invalid markup, duplicate id´s are not valid.

so use classes pls and therefore

getElementsByClassName()

to iterate over them

Since i already finished my demo

You wrote: trying getElementsByClassName() but nothing changes the reason for this is that getElementsByClassName() returns an array and you have to access each element of this array before you can use .style.backgroundColor="#ECF6A4";

function myFunction()
{
    var listItems = document.getElementsByClassName("even");
    for (var i = 0; i < listItems.length; i++)
    {
        listItems[i].style.backgroundColor="#ECF6A4"; // element i of array
    }
}

And the html

<ul>
  <li class="odd">1</li>
  <li class="even">2</li>
  <li class="odd">3</li>
  <li class="even">4</li>
  <li class="odd">5</li>
  <li class="even">6</li>      
</ul>
<button onclick="myFunction()">Change Color for even</button>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top