I have a series of buttons with a class called botonesSistema
I would like that when executing any function, they will change their class to another call EstadoSistemaEncendido
.
Try as follows:
var elements = document.getElementsByClassName("botonesSistema");
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].className = "estadoSistemaEncendido";
}
It happens that it only changes the class of the buttons in odd positions, there are 10 buttons and only the botoens: 1, 3, 5, 7, 9
turn green (effect of the class).
Often this error occurs in the console:
Cannot set property 'className' of undefined
And pressing again changes the class of the others.
With the above the buttons would handle two events, change color when pressed and also say the name of your id:
var elements = document.getElementsByClassName("botonesSistema");
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].classList.add("estadoSistemaEncendido");
elements[i].addEventListener("click",function(){
this.classList.toggle(".estadoSistemaApagado");
});
}
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function() {
var id = this.id.replace("es", "");
var mayus = id.charAt(0).toUpperCase();
var resto = id.slice(1);
var completo = mayus + resto;
var mensaje = "[Sistema: " + completo + "]";
alert(mensaje);
}
}
I add the CSS used and the HTML buttons:
.botonesSistema{
}
.botonesAparato{
}
.estadoSistemaApagado {
background-color: #f44336;
}
.estadoSistemaEncendido {
background-color: #4CAF50;
}
HTML:
<input type="button" id="1Accion" class="botonesSistema">
<input type="button" id="2OtraAccion" class="botonesSistema">