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
scrummy
7951 gold badge6 silver badges25 bronze badges
1 Answer 1
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.
Sign up to request clarification or add additional context in comments.
Comments
default
itemsis out of scope insetGreen. If it wasn’t,items.style.color === 'orange'still wouldn’t make sense becauseHTMLCollections don’t have astyleproperty. 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?document.getElementsByClassname('sid')but didn't workdocumentthat is calledgetElementsByClassname.