0

I have a <div> tag in which I add <table> dynamically through Javascript:

var htmlText = "<table id='table_" + id + "'><tbody>";
htmlText += "<tr> <td><img src='../../Icons/action_delete.gif' onclick='javascript:RemoveUser(\"" + id + "\");' /></td> <td>" +  name + " </td></tr>";
htmlText += "</tbody></table>";
document.getElementById("divSearchUsers").innerHTML += htmlText;

I add multiple table to the div. Now I want to remove a particular table. I get the ID of the table in RemoveUser function. How do I proceed for it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1509
  • 1,151
  • 5
  • 17
  • 45

4 Answers4

3

with relation to non jQuery:

Remove dom element without knowing its parent?

function removeElement(el) {
    el.parentNode.removeChild(el);
}
Community
  • 1
  • 1
Koenyn
  • 694
  • 4
  • 16
2

Since id of html element is supposed to be unique, you can directly delete it using remove methos.

With jQuery

$('#tableIdToRemove').remove();

With Javascript

tableIdToRemove = document.getElementById("tableIdToRemove");
tableIdToRemove.parentNode.removeChild(tableIdToRemove);

or

If you have html and there is chance of duplicate ID out side the parent table then you can access the table to delete in relation to its parent table as follow.

$("#divSearchUsers").find('#tableIdToRemove').remove();
Adil
  • 146,340
  • 25
  • 209
  • 204
  • 2
    For elements with an ID, just use `$('#tableIdToRemove')`. Under the hood, jQuery is going to use `document.getElementById` which will be faster and simpler than the second example you show. – calvinf Dec 14 '12 at 05:50
2

Get the element id and use remove()

$("#table_id").remove();
Doink
  • 1,158
  • 6
  • 10
2

if you want to remove the inner html then you should just do something like that:

document.getElementById('table_' + id).innerHTML = "";
user1855153
  • 579
  • 4
  • 15
  • 1
    @user1509 Please check this [`link`](http://stackoverflow.com/a/7332175/1577396).. might help you – Mr_Green Dec 14 '12 at 06:02