'eventlistener not working for dynamically created element [duplicate]

I have a simple section in which users can add input fields dynamically and users should be able to remove added input fields by clicking the delete button. am using vanilla js

here is a live demo : demo live codepen

HTML

<div id="domains-wrapper">
    <div class="input-group">
        <input name="domains" type="text" class="form-control domain-url" placeholder="Type valid url" value="" required="">
        <div class="valid-feedback">Looks good!</div>
        <button id="default-delete" style="display: none;" class="default-delete delete-input-el domain-btn btn-sm border border-1" type="button">
        </button>
        <button id="default-add" class="add-input-el added-input plus-button btn-sm border border-1 add_form_field" type="button">
            <span class="add-icon">+
            </span>
        </button>
    </div>
</div>

Js

var max_fields = 10;
var wrapper = document.getElementById("domains-wrapper");
var add_button = document.getElementById("default-add");

var x = 1;
add_button.addEventListener('click', function(e) {
    e.preventDefault();
    if (x < max_fields) {
        x++;
        $(wrapper).append('<div><input id="delete" type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
    } else {
        alert('You Reached the limits')
    }
})

var deleteBtn = document.querySelectorAll(".delete");

deleteBtn.forEach(function(e) {
    e.addEventListener('click', function() {
        console.log('PL')
      this.parentNode.remove(); //remove the whole div containing input and delete button
    })
});

Problem, Now when I click the delete button nothing is happening,

Any idea what am I missing here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source