0

I'm trying to build an event that would delete a row in my table.In every row I have delete button and applicable row should be deleted once button in this row is clicked. Is there a way to do it using 'this' property? I tried with calculating indexes for row and button but it was too confusing, I am looking for simpler code. Here is what I got till now, part with 'this' doesn't work obviously. Can you advise if there is similar way to select applicable row?

document.addEventListener("DOMContentLoaded", function () {

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

    function removeItem (e) {

        var rows = document.querySelectorAll("tr");

        rows[this].parentNode.removeChild(rows[this]);
    }

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", removeItem);
    }
 })
1
  • this is a button, has nothing to do with the rows and index... It you want to get the row, than just use parentNodes to you get to the row Commented Oct 27, 2016 at 14:46

1 Answer 1

1

this will refer to your .deleteBtn element. Assuming that's inside the row you want to remove, you need to traverse up that element's parents to find the tr, and then remove it:

function removeItem(e) {
    var tr = this;
    while (tr.tagName != "TR") {
        tr = tr.parentNode;
        if (!tr) {
            // Didn't find an ancestor TR
            return;
        }
    }
    tr.parentNode.removeChild(tr);
}

On modern browsers you could change the removeChild line to just:

tr.remove();

...but I have to admit I don't know how well-supported that is (I'm looking at you, Microsoft).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I didn't think that 'this' refers to button. I tried reaching tr with this.parentElement.parentElement and that worked.
@Joanna: That will work until/unless you change your structure; it's more robust to search as above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.