Change the Background of all Elements in a Class

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

    You just need to loop and apply styles. Your code is partially correct, some error though, see error at end.

    var myCounters = document.getElementsByClassName("counter")
    
    function myFunction() {
      for (var i = 0; i < myCounters.length; i++) {
        console.log(myCounters[i])
    
        myCounters[i].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;
    }




    some button

    var myCounters = document.getElementsByClassName(counter)

    counter should be a string - the name of class

    var i - 0

    This should be var i = 0;

    conole.log(myCounters[i])

    Typo - its console

    document.getElementsByClassName(i).style.backgroundColor = "red"

    variable i is not accessible in myFunction - scope issue

提交回复
热议问题