0

I have a program that creates a table every time I press a button.

The page keeps creating duplicate tables on click.

I am trying to delete/remove/replace the table if it exists but it doesn't do anything.

I have tried the following code

document.getElementById("paragraphDOM").outerHTML = "";
            document.getElementById("paragraphDOM").remove();
            document.getElementById("paragraphDOM").removeChild(tbl);
            document.getElementById("paragraphDOM").blur;
            document.getElementById("paragraphDOM").innerHTML = "";

None of these gets rid of the original table, I even tried creating a paragraph and adding the table to it and then removing it as I got an error trying to set outer html to "" that it needed a parent.

2
  • Check the return of getElementById before using it, it may not be valid. Commented Jan 15, 2019 at 13:27
  • What is the if of your table ? Commented Jan 15, 2019 at 13:29

3 Answers 3

1

If you're using MSIE you have to reference the table's parent to be able to remove the node:

let table = document.getElementById('#mytable');
let parent = table.parentNode;
parentNode.removeChild(table);

otherwise in all other current browsers you should be able to just use .remove:

let table = document.getElementById('#mytable');
table.remove();

See also caniuse.com for more detailed browser support information.

Sign up to request clarification or add additional context in comments.

3 Comments

I created the following page
The js for what you gave me is jsfiddle.net/rvermaak/2qp01wno/3 But my page jsfiddle.net/rvermaak/humnoejL/3 Keeps creating more tables I know it has to be something stupid I'm doing , but I can't see it.
@Robert your fiddle doesn't work, and it's far too long for me to bother debugging. please create a small self contained example with the bare minimum of code that demonstrates the issue. Chances are you'll spot what you've done wrong then anyway...
0

Just use parentNode to define the parent of table then apply removeChild() on it

var tbl=document.getElementById("paragraphDOM");
if(tbl) tbl.parentNode.removeChild(tbl);

Comments

0

As long as your variable tbl is correctly defined as the table you want to remove, this will remove it:

tbl.parentNode.removeChild(tbl);

If you already have the new table ready to replace tbl, let's call it newTbl here, you can simply do this:

tbl.parentNode.replaceChild(newTbl,tbl);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.