I have a function that inserts a class to the buttons, this class changes their color, only this function can't be set to all of them so that the class is added as the button is clicked.
It only works with one, and I also need to click the 'color' button so that it changes color and I want to add the class to the button that clicks it, without the need for another, all this with javascript
function color() {
var color = document.querySelector(".buttons button");
color.classList.toggle("edit");
}
.edit{
background-color: #ff0 !important;
}
<div class="buttons">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
<br>
<button onclick="color()">color</button>
Here is the code in pure JS and its explanation:
Run the snippet so you can see it working.
I also leave you how to do it with JQuery:
document.querySelector
document.querySelectorAll
Bearing this in mind, you can assign the
onclick
to each of the buttons with aforEach
, and by the way totoggle
change them with aforEach
.A possible solution through the use of only CSS and its useful pseudo-classes:
This is my answer: First I select all the buttons located inside an element that has the class
.buttons
.After for each button (color)
buttons.forEach
when clicking the button
button.addEventListener("click",...
add or remove the class
.edit
:button.classList.toggle("edit");
I hope this is what you were asking.
This is a way to do it by assigning an id to the buttons, when clicking you change the color of the cell using the rgba class: