简体   繁体   中英

DOM: Delete newly created 'article' element with newly created delete button within onclick event?

I have one section element that contains one article element. Also, I have one input button with 'onclick' event. Whenever this event fired, a new article element appended to the section element with unique id . The newArticle element contains a label, text box and a delete button. All these three elements get created within the on-click event.

document.getElementById("addRow").onclick = function () {

    var newCustomerlbl = document.createElement("label");
    newCustomerlbl.innerHTML = "Cutomer Name: ";
    var newCustomertxt = document.createElement("input");
    newCustomertxt.setAttribute("type", "text");

    var delBtn = document.createElement("input");
    delBtn.setAttribute("type", "button");
    delBtn.setAttribute("value", "Delete");
    delBtn.setAttribute("id", "btnDelete");

    var newArticle = document.createElement("article");
    newArticle.appendChild(newCustomerlbl);
    newArticle.appendChild(newCustomertxt);
    newArticle.appendChild(delBtn);

    var customerSection = document.getElementById("customerRecords");

    var customerArticles = customerSection.getElementsByTagName("article");

    for (var i = 0; i < customerArticles.length; i++) {

        var lastDigit = i + 1;

        var newArticleValue = "article" + lastDigit;
        newArticle.setAttribute("id", newArticleValue);
    }

    customerSection.appendChild(newArticle);
}

Now what I want is whenever user click upon the newly created appended delete button, only that particular article get deleted without effecting the rest of articles.

Here is the my jsFiddle code.

You need to bind an event listener on the newly created delete button. Your example code about using $(this) suggest that you are using JQuery, but then again in the rest of the code you are not using any JQuery?

If you are using JQuery, things get real simple, just add something like

$(document).on('click','.btnDelete', function(){
   $(this).closest('article').remove();
});

(and remember to give the deletebutton a CLASS rather than ID, as there will be multiple delete buttons).

If you are NOT using JQuery, you need to add the event listener EVERY TIME a new delete button is created

newArticle.appendChild(delBtn);
delBtn.onclick = function(.....

etc.

If you don't want to use jQuery you can add event listeners to your buttons:

delBtn.addEventListener('click', function () {
    this.parentElement.remove();
}, false);

https://jsfiddle.net/3nq1v5e1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM