Search code examples
javascriptgetelementsbyclassname

How can I invoke all instances of a class name in a function?


I'm trying to cause all elements with the same class name ("Cappy") to change color when this function is invoked, but the only way I know how to invoke all of them is by writing out a line with the variable (myPara) and an index number for each one, and as there are many of them this seems clumsy. Is there a simpler way to do this?

function mouseoverCaroline(){
    var myPara = document.getElementsByClassName("Cappy");
    myPara[0].style.backgroundColor = "red";
    myPara[1].style.backgroundColor = "red";
    myPara[0].style.color = "black";
    myPara[1].style.color = "black";
    myPara[0].style.borderColor = "#94a0b4";
    myPara[1].style.borderColor = "#94a0b4";
}

Solution

  • Something like this:

    function mouseoverCaroline(className) {
        var myPara = document.getElementsByClassName(className);
        Array.from(myPara).forEach(element => {
          element.style.backgroundColor = "red";
          element.style.backgroundColor = "red";
          element.style.color = "black";
          element.style.color = "black";
          element.style.borderColor = "#94a0b4";
          element.style.borderColor = "#94a0b4";
        });
    }
    div {
      border: 1px solid black;
      margin: 1px;
      width: 100px;
    }
    <button onClick="mouseoverCaroline('Cappy')">Click Me</button>
    <div class="Cappy">Div 1</div>
    <div class="Cappy">Div 2</div>
    <div class="Cappy">Div 3</div>
    <div class="Cappy">Div 4</div>
    <div class="Cappy">Div 5</div>
    <div class="Cappy">Div 6</div>