Home > Back-end >  When you click on "Add a button", a new button should be added on the screen, with the &qu
When you click on "Add a button", a new button should be added on the screen, with the &qu

Time:07-09

I can add a button but how to increase its number on each click, (in javascript).

CodePudding user response:

let counter = 0 // counter for buttons
const button = document.createElement('button') // create main button
button.addEventListener('click', () => { //listens for click event on main button
  const newButton = document.createElement('button') // creates new button
  newButton.textContent = `Button ${  counter}` // adds text to the new button
  document.body.appendChild(newButton) // adds new button to the body
})
button.textContent = 'Add a button' // adds text to the main button
document.body.appendChild(button) // adds main button to body

CodePudding user response:

There are many possibilities, such as :

let clickNumber = 0;
function addButton(clickedButton) {
  clickNumber  ;
  const newButton = document.createElement("button");
  newButton.innerText = `NewButton ${clickNumber}`;
  document.querySelector("body").insertAdjacentElement('beforeend', newButton);
}
<button onclick="addButton(this)">click me</button>

  • Related