Change the Background of all Elements in a Class

前端 未结 5 1912
慢半拍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:57

    Hi you can do this using for/of iteration on DOM lists such nodeList or HTMLCollection. since all recent versions of modern browsers (Safari, Firefox, Chrome, Edge) support it

    function myFunction() {
       let counters = document.getElementsByClassName("counter");
       for(let counter of counters){
         counter.style.backgroundColor = 'red';
       }
    }
     .counter {
        width: 100px;
        height:100px;
        background-color:orange;
    }
    #btn {
        background-color:aqua;
        width:50px;
        height:50px;
        position:absolute;
        left:200px;
        top:10px;
    }
     




提交回复
热议问题