0

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.

2
  • 1
    Since you are using getElementByClassName it will be accessed by array. you need to do like document.getElementsByClassName("pls-work")[0].style.background = color; or some loop Commented Oct 21, 2021 at 5:08
  • 1
    I don't know where you've searched, but this is the MDN doc about getElementsByClassName method, and should be within the first 3 results if you search for the method name in Google. Anyway, you've got multiple answers pointing you the same direction, so accept one of them and be done with it. Commented Oct 21, 2021 at 5:14

7 Answers 7

1

Please Try With this,

first get that element in variable and the loop on it.

function changeBackground(color){
    var elements = document.getElementsByClassName("pls-work")
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.background=color;
        }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for taking the time to write this! This is exactly what I need. Although there's a lot of helpful answers below, I don't know how to use them cause I'm not yet good with JavaScript... so thank you!
1

The call to document.getElementsByClassName("pls-work") returns an HTMLCollection of elements not a single element. You need to iterate over the collection and set the style property on each element.

See JS: iterating over result of getElementsByClassName using Array.forEach

Comments

1

The getElementsByClassName method returns a collection (NodeList) object, see the docs here. To do what you want to do, you'll have to do the following:

function changeBackground(color) {
    let elements = document.getElementsByClassName("pls-work")

    for (let i = 0; i < elements.length; i++) {
        elements.item(i).style.background = color
    }
}

See the docs as listed above for more information on how to iterate over this collection.

Comments

1

getElementsByClassName returns the list of elements , so you can do it two ways

1.mentioning index value in javascript like below snippet

function changeBgColor(color){
        document.getElementById("background1").style.background = color;
    }
 
    function changeBackground(color){
        document.getElementsByClassName("pls-work")[0].style.background = color;
document.getElementsByClassName("pls-work")[0].style.background[1] = 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>

  1. Do iterate over the elements of particular class and add a background color to it

Comments

1

getElementsByClassName returns an “array-like object” of elements which you need to iterate over - as opposed to getElementById which returns a single element.

Check this out:

const changeBgColor = () => {
  const elements = document.getElementsByClassName('color-me');
  const color = document.querySelector('input').value;
  for (let i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = color;
  }
};
<p class='color-me'>Color me!</p>
<p>Can't change me..</p>
<p class='color-me'>Me too!</p>
<input type=color />
<button onclick=changeBgColor()>Click Me</button>

Comments

1
function changeColor() {
  let cols = document.getElementsByClassName('col1');
  for(i = 0; i < cols.length; i++) {
    cols[i].style.backgroundColor = 'blue';
  }
}
//maybe type script gives error about style just use //@ts-ignore

Comments

0

Do you just want to change the background-color of the first element?

I prefer to use querySelector

ES5

function changeBackground(color) {
    document.querySelector(".pls-work").style.backgroundColor = color;
}

But if you want to apply all the elements, use getElementsByClassName and forEach

function changeBackground(color){
    document.getElementsByClassName("pls-work").forEach(e => {
        e.style.backgroundColor: color;
    });
}

Notice: if you want to change only background color, use backgroundColor

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.