No matter how I try it, I can't make it work. If I use .getElementById
, it works... but I need to target multiple divs
so I need to use .getElementsByClassName
.
Here's what I have so far:
function changeBgColor(color){
document.getElementById("background1").style.background = color;
}
function changeBackground(color){
document.getElementsByClassName("pls-work").style.background = color;
}
#background1{
background: #c0c0c0;
padding: 50px;
color: #fafafa;
}
.background2{
background: #ff7f50;
padding: 20px;
}
.background3{
background: #555;
padding: 20px;
}
<h4>First example</h4>
<div id="background1"><p>My background color will change.</p></div>
<button onclick="changeBgColor('#222');">This function will work, no problem</button>
<br><br>
<h4>Second example</h4>
<div class="background3 pls-work"><p>My background color and my sibling's won't.</p></div>
<div class="background2 pls-work"><p>I am the sibling</p></div>
<button onclick="changeBackground('#222');">This will not work</button>
I've been searching everywhere but I can't find one where they use class
instead of id
.
I would appreciate any pointers on what I'm doing wrong with this.