Change the Background of all Elements in a Class

前端 未结 5 1991
慢半拍i
慢半拍i 2021-01-28 05:25

I have a div, when I clicked on it, should turn all the elements in the .counter class to red, but at the moment it does nothing. I believe you have to run through a loop first

5条回答
  •  感动是毒
    2021-01-28 05:50

    In addition to the given answers, I would suggest to apply style changes by adding a class to the elements and going about it via CSS. Applying inline styling takes up some more performance.

    function myFunction() {
        var myCounters = document.getElementsByClassName("counter")
        for (var i = 0; i < myCounters.length; i++) {
            console.log(myCounters[i])
            myCounters[i].classList.toggle('red');
            //using '.toggle' will remove the class again upon clicking the button and re-add when clicking again, and so forth. Replace .toggle by .add to only add the class if that's your use-case.
        }
    }
    

    And then in your CSS

    .counter {
        width: 100px;
        height: 100px;
        background-color: orange;
    }
    .counter.red {
        background-color: red;
    }
    

    If only doing this for a few elements on the page, the performance drawback is negligible. If you're doing this for a lot of elements, i'd suggest doing it via CSS.

提交回复
热议问题