Alex Pereira
Alex Pereira

Reputation: 36

remove table row from html with jquery

i would like to remove a row from a table using jQuery. Here is the html:

<tr>
    <td><center><a id="remove" href="#"><span class="glyphicon glyphicon-remove"></span></a></center></td>
</tr>

my jquery script:

$('td a').on('click',function(e){
//delete code.
e.preventDefault();
$(this).parent().remove();

});

when i click on the link, nothinh happens. Anybody can help me?

Upvotes: 0

Views: 51

Answers (1)

j08691
j08691

Reputation: 207901

You need to either wrap your code in a $(document).ready call or move it to the end of the page before the closing body element (</body>). If you're executing that code in the head of your document you're running it against elements that don't yet exist.

Also if you want to remove the parent row, use $(this).closest('tr') instead of $(this).parent() as that would select the non-standard <center> element.

$(document).ready(function() {
  $('td a').on('click', function(e) {
    //delete code.
    e.preventDefault();
    $(this).closest('tr').remove();
  });
});

jsFiddle example

Upvotes: 1

Related Questions