0

I want to make a program that changes the selected elements color on clicks. For example: First click > Green. Second click > Blue. Third click > Default color (orange). I stucked in an error and I don't know how to fix it. Any idea how to make it?

function changeColor(className, colorValue) {

    var items = document.getElementsByClassName(className);
  for (var i=0; i < items.length; i++) {
    items[i].style.color = colorValue;
  }

}

function setGreen () {
if (items.style.color === 'orange') {
    changeColor("sid", "red");
}
}
.sid {
  color: orange;
}
<span class="sid">STH</span><br>
<span class="sid">STH</span><br>
<span class="sid">STH</span><br>
<span class="sid">STH</span><br>
<br>
<button onclick="setGreen()">Change Color</button>
scrummy
  • 795
  • 1
  • 6
  • 20
  • 1
    `items` is out of scope in `setGreen`. If it wasn’t, `items.style.color === 'orange'` still wouldn’t make sense because `HTMLCollection`s don’t have a `style` property. See [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/q/10693845/4642212). Why not just change the class name of a parent element and define all colors in CSS? – Sebastian Simon Feb 22 '21 at 21:04
  • I also tried it with `document.getElementsByClassname('sid')` but didn't work – scrummy Feb 22 '21 at 21:04
  • 1
    @scrummy There is no method on `document` that is called `getElementsByClassname`. – Sebastian Simon Feb 22 '21 at 21:04
  • Then how should I refer to it? – scrummy Feb 22 '21 at 21:06
  • @scrummy Refer to what? – Sebastian Simon Feb 22 '21 at 21:06
  • How can I refer to the `items` to change its color? – scrummy Feb 22 '21 at 21:07
  • `items` does not have a color. `items` isn’t an element. You’re already correctly changing colors in `changeColor`. The color check in `setGreen` is just wrong. You could use `document.getElementsByClassName("sid")[0].style.color` to compare, but there are better ways. – Sebastian Simon Feb 22 '21 at 21:09

1 Answers1

0

The error is that the function setGreen() can't get the variables of the function changeColor(className, colorValue). You can change setGreen() into something like this:

 function setGreen() {
    var items = document.getElementsByClassName("sid");      
    for (var i = 0; i < items.length; i++) {           
        if (items[i].style.color === 'orange') {
            changeColor("sid", "red");
        }
    }
   
}

now the function knows what the items are and can work with them.

Onlime
  • 26
  • 4