0

I am trying to remove a row which is actually in a DIV.

var html =
"<div class=\"product\" id=\"" +
                data.tasks[j].cart_id +
                "\"><div class=\"product-image\"><img src=\"images/albums/" +
                data.tasks[j].album_img +
                "\"></div><div class=\"product-details\"><div class=\"product-title\">" +
                data.tasks[j].song_name +
                "</div><div id=\"cart1\"></div></div><div class=\"product-price\">" +
                data.tasks[j].price +
                "</div><div class=\"product-quantity\"><input type=\"text\" value=\"2\" min=\"1\"></div><div class=\"product-removal\"><button class=\"remove-product\" onclick=\"removeItem1(" +
                data.tasks[j].cart_id +
                ")\">Remove</button></div><div class=\"product-line-price\">" +
                data.tasks[j].price +
                "</div></div>";
            $(html).appendTo("#cart1");

These are in a while loop. So it creates more than 1 row.

function for remove button is

function removeItem1(val) {
         //$(this).closest("div").remove();
        a = document.getElementById(val);
                        removeItem(a);
                    }

and in html I call the div by <div id="cart1"></div>

But when I click on the remove button all DIVs get removed. Not sure what I am doing wrong.

  • you need to ensure you only use the div ID. not the `div` element || class into `removeItem1()` It sounds like you're passing in `DIV` as the element to remove, OR you have multiple of the same `id`'s which is a big no no – Pogrindis Jul 27 '15 at 15:57

2 Answers2

0

You can use .parent() twice to get de parent element.

function removeItem1(val) {
    // Get the parent DIV. It's twice to get DIV class product
    var e = $(this).parent().parent();
    e.remove();

}

Or with .closest()

function removeItem1(val) {
    $(this).closest(".product").remove();
}

Tell me if i had an error or you have a question.

vnponce
  • 121
  • 1
  • 6
0

What if you try removing it from its parent element?

var a = document.getElementById(val);

a.parentNode.removeChild(a);

Here are some more details about deleting objects with JavaScript: Remove element by id

Community
  • 1
  • 1
StronglyTyped
  • 2,134
  • 5
  • 28
  • 48