skip to Main Content

I want to click on any of the 3 buttons, and they all will change their background colors at the same time. What is missing or needed to change in my code, for the addEventListener to be able to apply in all elements with the same class?

const one = document.getElementsByClassName('one');

one.forEach((element) => {    
    element.addEventListener("click", () => {
      if (element.style.backgroundColor = "#DCDCDC") {
        element.style.backgroundColor = "#56F1FF";
      } else {
        element.style.backgroundColor = "#DCDCDC";
      }
     })
 });
.one {
  background-color: #DCDCDC;
}

.one:hover {
  background-color: #56F1FF;
}
<button class="one">Catch</button>
<button class="one">Change</button>
<button class="one">Choose</button>

4

Answers


  1. I clicked the "Run Code Snippet" button on your code and it returned with an error: "one.forEach is not a function" that’s your problem. try something different like a for loop or a while loop with variables (same thing). It may autocorrect into forEach for you if you have a library installed but you’re better off using a default javascript function

    Login or Signup to reply.
  2. The call document.getElementsByClassName returns an array-like object, but not an array. See: MDN – getElementsByClassName

    The function forEach can only be called on an array.

    To fix this, you need to create an array from the array-like object, which can be achieved by using Array.from. See: MDN – Array.from

    Update your JavaScript like this:

    const one = Array.from(document.getElementsByClassName('one'));
    
    Login or Signup to reply.
  3. There are couple of things wrong here.

    1. document.getElementsByClassName returns a HTMLCollection that doesn’t have access to forEach method. You have to convert it into an array before using forEach.

    2. element.style.backgroundColor returns a RGB value, you can’t compare it with HEX code.

    Here is the correct way to fix this

    const btnCollection = document.getElementsByClassName('one');
    const buttons = Array.from(btnCollection);  // Convert to an array
    
    buttons.forEach((element) => {
        element.addEventListener("click", () => {
            if (element.style.backgroundColor === "rgb(220, 220, 220)") {  
                buttons.forEach((btn) => btn.style.backgroundColor = "#56F1FF");  
            } else {
                buttons.forEach((btn) => btn.style.backgroundColor = "#DCDCDC");  
            }
        });
    });
    
    Login or Signup to reply.
  4. As explained .forEach() doesn’t exists on HTMLCollection returned from getElementsByClassName.

    But I would recommend potentially better approach of using a container:

    document.getElementById('container').addEventListener('click', e => {
      e.target.matches('button') && 
      e.currentTarget.classList.toggle('alternate-bg');
    });
    #container button {
      background-color: #DCDCDC;
    }
    
    #container button:hover {
      background-color: #56F1FF;
    }
    #container.alternate-bg button{
      background-color: #56F1FF;
    }
    <div id="container">
    <button>Catch</button>
    <button>Change</button>
    <button>Choose</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search