amlane86
amlane86

Reputation: 668

How to remove elements in HTML from Javascript?

I have a javascript function that appends elements into my HTML page. I want to add a function that when a user clicks a button in HTML it will remove the associated HTML content from the page.

$("#keywords").append("<td><img src=\"images/delete.png\" class=\"delete_filter\" /> " + id + "</td>");

The code above is how I am adding elements to the HTML. So in this case when a user clicks the appended image <td><img src=\"images/delete.png\" class=\"delete_filter\" /> will be removed from the HTML.

This is what I have now that isn't working:

$(".delete_filter").click(
function(){
    ($(this).parent()).remove();
});

Upvotes: 0

Views: 312

Answers (6)

JaredPar
JaredPar

Reputation: 754715

The problem appears to be that you're adding the click handler before the DOM element is added to the page. Hence it's not binding to that element. Try using on instead

$('table').on('click', '.delete-filter', function() {
  $(this).parent().remove();
});

The on API is new to jQuery 1.7. If you're using an earlier version then try live

$('table').delegate('.delete-filter', 'click', function() {
  $(this).parent().remove();
});

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

Because the element is being dynamically added click() will not work as it only sees elements which were available on load.

Try this instead:

$("#myTable").delegate(".delete_filter", "click", function() {
    $(this).parent().remove();
})

Or in jQuery 1.7+

$("#myTable").on("click", ".delete_filter", function() {
    $(this).parent().remove();
})

Upvotes: 2

Wesley
Wesley

Reputation: 2264

Try:

$('#keywords').on('click', '.delete_filter', function() {
    $(this).parent().remove();

});

Probably your code doesn't work because the delete_filter class objects aren't there yet when the code is executed. The on syntax binds it dynamic so it should work..

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

Try this: Bind the event after appending the item to DOM.

$("#keywords").append("<td><img src=\"images/delete.png\" class=\"delete_filter\" /> " + id + "</td>");
$(".delete_filter").click(function() {
    $(this).parent().remove();
});

Upvotes: 0

Downpour046
Downpour046

Reputation: 1671

Try this

$(document).ready(function(){

    $("#keywords").append("<td><img src=\"images/delete.png\" class=\"delete_filter\" /> "  + id + "</td>");

    $(".delete_filter").on("click", function(event) {

     // Not sure why you had this section wrapped in a function() tag, wasn't necessary
     $(this).parent().remove();

    });
});

Upvotes: 0

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

The elements won't be part of the html at the point you set up your event listeners, try the following:

$('table').delegate('.delete_filter', 'click', function() {
  $(this).parent().remove();
});

Upvotes: 1

Related Questions