0

As long as I limit myself to selecting a single ID this code will run correctly. Problem is that when I'm using getElementsByClassName to apply the same click function to the whole class, I get that style is undefined... I've tried different things, but nothing works. I've put both versions of the code here. The first works, but the second won't. Is there something I'm not seeing?

I've put both versions of the code here. The first works, but the second won't. Is there something I'm not seeing?

This is the first version and will work on a single element:

var cardTitle = document.getElementById("testCard");
var cardBackground = document.getElementById("testBack");
cardBackground.style.backgroundColor = "rgb(102, 102, 102)";

function toggleColor() {
    if(cardBackground.style.backgroundColor == "rgb(102, 102, 102)") {
        cardBackground.style.backgroundColor = "rgb(218, 164, 65)"
    } else {
        cardBackground.style.backgroundColor = "rgb(102, 102, 102)"
    }

}

cardTitle.addEventListener("click", toggleColor);

This is the version with classes that doesn't work. Now the style inside the if/else will be undefined...

var cardTitle = document.getElementsByClassName("custom-collapse-btn");
var cardBackground = document.getElementsByClassName("card-section");

for (i = 0; i < cardBackground.length; i++) {
    cardBackground[i].style.backgroundColor = "rgb(102, 10, 102)";

}

function toggleColor() {
    if(cardBackground.style.backgroundColor == "rgb(102, 102, 102)") {
        cardBackground.style.backgroundColor = "rgb(218, 164, 65)"
    } else {
        cardBackground.style.backgroundColor = "rgb(102, 102, 102)"
    }

}

for (let n = 0; n < cardTitle.length; n++) {
    cardTitle[n].addEventListener("click", toggleColor);

}

I'd like to toggle the color on click to all elements of the same class. It works using a single element and targeting the Id with getElementByID(), but as I switch to class and loops style is undefined no matter what I do. Any help would be greatly appreciated :)

  • `cardBackground = document.getElementsByClassName("card-section");` makes it a collection, not an element, so it doesn't have a `style.backgroundColor` property - you'll see an error thrown. You probably want to access `cardBackground[i].style.backgroundColor` (and use `let` to declare your `i` in the loop) – CertainPerformance Sep 06 '19 at 01:54
  • `cardBackground` is a collection, you have to index it, like you do in the `for` loop. – Barmar Sep 06 '19 at 01:54

1 Answers1

0

In an event listener, this will be the target of the event.

function toggleColor() {
    if(this.style.backgroundColor == "rgb(102, 102, 102)") {
        this.style.backgroundColor = "rgb(218, 164, 65)"
    } else {
        this.style.backgroundColor = "rgb(102, 102, 102)"
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612