skip to Main Content

Button click event does not work in javascript. I have a div with a box id. When I try to assign an onclick to each button, only the last button works properly, the other buttons do not work.

Also, this is a simplified version of my code to explain. I should definitely use innerHTML in the original code. But as long as I’m using innerHTML, the code doesn’t work

also here is my html code:

id = (x) => {
  return document.getElementById(x)
};

let box = id('box')

btn = (text, func) => {
  var button = document.createElement('button');
  button.innerHTML = text;
  button.onclick = func;
  box.appendChild(button)
}

render = () => {

  for (let i = 0; i < 5; i++) {
    box.innerHTML += '</br>'
    btn('btn ' + i, () => {
      console.log(1)
    })
  }

}

render()
<!-- Project -->
<div id="box"></div>

2

Answers


  1. With box.innerHTML += '</br>' you actually do:

    box.innerHTML = box.innerHTML + '</br>';
    

    …which just re-assigns a new HTML string, thereby losing any binding of event handlers.

    Instead do the same for the br elements as you do for the button elements, and replace the above statement with this:

      box.appendChild(document.createElement('br'));
    

    Alternatively, you can maybe just omit the br elements, and instead style your buttons to have a "block" style. Like in your CSS you could have

    #container > button { display: block }
    

    This assumes those buttons are direct children of some element with id container. Adapt as needed for your case.

    Login or Signup to reply.
  2. Alternatively, if you really want to keep most of your current code, you can use .insertAdjacentHTML() instead of .innerHTML like this:

    id = (x) => {
      return document.getElementById(x)
    };
    
    let box = id('box')
    
    btn = (text, func) => {
      var button = document.createElement('button');
      button.innerHTML = text;
      button.onclick = func;
      box.appendChild(button)
    }
    
    render = () => {
    
      for (let i = 0; i < 5; i++) {
        box.insertAdjacentHTML('beforeend','<br>');
        btn('btn ' + i, () => {
          console.log(i)
        })
      }
    
    }
    
    render()
    <!-- Project -->
    <div id="box"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search