Unique class per click javascript

Question:

I have a function that inserts a class to the buttons, this class changes the color of the buttons, only this function can not put it to everyone so that everyone adds the class as they click.

It only works with one, and I also need to click the 'color' button so that it changes color and I'm looking to add the class to the button that you click, 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>

Answer:

Here is the code in pure JS and its explanation:

// Seleccionanos todos los botones
let buttons = document.querySelectorAll(".buttons button");

// Creamos un listener para cada botón, y ordenamos que cambie la clase cuando se le da clic al botón
buttons.forEach(button =>{
  button.addEventListener("click",_ =>{
    button.classList.toggle("edit");
  })
})


//Si lo que quieres es que solo el botón presionado tenga la clase

let buttons2 = document.querySelectorAll(".buttons2 button");

buttons2.forEach(button =>{
  button.addEventListener("click",_ =>{
    buttons2.forEach(button =>{
      button.classList.remove("edit");
    })
    button.classList.toggle("edit");
  })
})
body{
height: 100vh;
margin: 0;
}
.buttons{
height: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.buttons2{
height: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.edit{
color: #fff;
background-color: blue !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="buttons">
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <button>4</button>
  <button>5</button>
</div>

<div class="buttons2">
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <button>4</button>
  <button>5</button>
</div>

Run the snippet so you can see it working.

I also leave you how to do it with JQuery:

$(".buttons button").click(function(){
    $(this).toggleClass("edit");
});

//Si quieres que solo quede activo al que le das clic y que los demás queden con su estilo normal prueba con el siguiente grupo de botones:

$(".buttons2 button").click(function(){
    $(".buttons2 button").removeClass("edit");
    $(this).toggleClass("edit");
});
Scroll to Top