There is an n-th number of buttons created by the loop. In the same place, they are assigned an id and a setClass (id) function. This function changes the color of this button several times:

/* Цикл создающий таблицу из буттонов */ button.setAttribute("id", id); button.setAttribute("onclick", "setColorClass('"+id+"')"); function setColorClass(id) { var elem = document.getElementById(id); if (elem.className == "firstClass") { elem.setAttribute("class", "SecondClass"); } else if (elem.className == "SecondClass") { elem.setAttribute("class", "ThirdClass"); } etc... 

I need: so that when I click on one button, an attribute with a sequence number is assigned to it. When you click on some other button: the next number and so on. It is impossible that when you click on one and the button, the numbers are moved. One button is the same digit.

enter image description here

  • Create a global variable, for example var i = 1 . When you click on a button, check whether your attribute has an element; if it doesn’t have one, then create it with a value of i , then add one to i ( i++ ). - mix
  • not quite clear what should assign? - C.Raf.T
  • @ C.Raf.T element attribute number: elem.setAttribute("number", number) - Zhi V

1 answer 1

Well, if I understood correctly:

 var classArray = ["firstClass", "SecondClass", "ThirdClass", "firstClass", "SecondClass", "ThirdClass"]; var xx = document.getElementById("xxx"); function setColorClass(id) { let elem = document.getElementById(id); if (!elem.hasAttribute("class")) { elem.setAttribute("class", classArray[0]); classArray.shift(); let num = 6 - classArray.length; elem.setAttribute("number", num); elem.innerHTML = num; } } for (let i = 0; i < 6; i++) { let btn = document.createElement("BUTTON"); btn.setAttribute("id", i); btn.setAttribute("onclick", "setColorClass('" + i + "')"); xx.appendChild(btn); } 
 button { width: 50px; height: 50px; color: #fff; } .firstClass { background: red; } .SecondClass { background: green; } .ThirdClass { background: blue; } 
 <div id="xxx"></div>