1

Here Im facing a strange problem. I have a button which when clicked inserts <h1>Hello</h1> to a target element. I found out that the click only works once and doesn't show any errors. Im not able to figure out why its not working.

Here's my code

const addMore = document.querySelector('#addMore');
let parentElem = document.querySelector('#target');
addMore.addEventListener('click', function() {
  parentElem.innerHTML += `
        <h1>hello</h1>
        `
})
<div class="col-md-12" id="target">
  <div class="row">
    <div class="col-md-2 mb-3">
      <div class="form-group">
        <label for="price" class="form-label small">Price</label>
        <div class="input-group">
          <span class="input-group-text">₹</span>
          <input type="number" name="price" id="price" class="form-control" placeholder="100">
        </div>
      </div>
    </div>
    <div class="col-md-2 mb-3 d-flex align-items-end">
      <button type="button" class="btn btn-primary" id="addMore">+ Add More</button>
    </div>
  </div>
</div>
Joy Dey
  • 563
  • 1
  • 5
  • 17
  • I was just going to answer; the problem is that your button is inside the target element, and editting `innerHTML` causes all the inner html to be re-rendered, causing any event listeners on elements inside it to be lost. So it is re-rendered as a plain old button, unaware that a previous render got an event listener. I see a moderator has linked a duplicate that explains in more detail with some pointers on what to do. – user56reinstatemonica8 Mar 02 '22 at 10:13
  • A tip for debugging things like this: put `debugger` or `console.log` in the function that is failing without errors so you can see if it is being run or not and if it is, you can see what's going on at that point. A `console.log` inside the onClick function would show you that the function isn't called at all after the first time, which narrows the question from "why isn't this working" to "why isn't this event listener being called after the HTML is re-written", which is half way to the answer – user56reinstatemonica8 Mar 02 '22 at 10:15
  • 1
    I actuallly called `console.count()` but I forgot the fact that the whole html block is re-rendered. Thanks @user56reinstatemonica8 – Joy Dey Mar 02 '22 at 10:17

0 Answers0