Search code examples
javascripthtmlcssgetelementbyidgetelementsbytagname

How do i use document.getElementById("mydiv") to edit multiple divs with the same ID


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?


Solution

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

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