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>

asked Feb 22, 2021 at 21:00
7
  • 1
    items is out of scope in setGreen. If it wasn’t, items.style.color === 'orange' still wouldn’t make sense because HTMLCollections don’t have a style property. See What do querySelectorAll and getElementsBy* methods return?. Why not just change the class name of a parent element and define all colors in CSS? Commented Feb 22, 2021 at 21:04
  • I also tried it with document.getElementsByClassname('sid') but didn't work Commented Feb 22, 2021 at 21:04
  • 1
    @scrummy There is no method on document that is called getElementsByClassname. Commented Feb 22, 2021 at 21:04
  • Then how should I refer to it? Commented Feb 22, 2021 at 21:06
  • @scrummy Refer to what? Commented Feb 22, 2021 at 21:06

1 Answer 1

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.

answered Feb 22, 2021 at 23:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.