Tony Vitabile
Tony Vitabile

Reputation: 8594

Deleting a row from an HTML table in javascript

I have javascript code that manages an HTML table. The code needs to be able to delete a row from an HTML table.

I am currently using the following code to delete the row:

var rowToDelete = ...;

if (rowToDelete)
    rowToDelete.remove();

This works fine in Firefox & Chrome, however, when I load the page in IE 11 & bring up the javascript debugger, it displays

Object doesn't support property or method 'remove'

I haven't tried this code in earlier versions of IE yet.

How can I do this in a cross-browser manner? My page does have jQuery included so I can use a jQuery method.

Upvotes: 0

Views: 302

Answers (3)

A1rPun
A1rPun

Reputation: 16837

Chrome supports .remove() on elements.
You should do:

rowToDelete.parentNode.removeChild(rowToDelete);

If you want this functionality in IE you can add the function to the HTMLElement prototype.

HTMLElement.prototype.remove = function (){
    this.parentNode.removeChild(this);
}

Upvotes: 3

Danny
Danny

Reputation: 7518

If it is a dom element you can do

$(rowToDelete).remove();

Upvotes: 0

Ringo
Ringo

Reputation: 3965

Make sure your rowToDelete is an jQuery Object, like this:

var rowToDelete = $('tr');
rowToDelete.remove();

Upvotes: 1

Related Questions