简体   繁体   中英

how to delete a created table using javascript

I am having a hard time to figure out the solution. I have created two buttons in HTML. One to add table and the other to remove table. The corresponding onclick functions for the buttons are written in the <script> tags. Now onclicking the Add Table button, the table would be created. And on clicking the Remove Table button the above created table should be deleted. I haven't figured out how to remove the created table. Please help me out in the solution to remove the created table. Below is the code for the following.

HTML CONTENT:

<!DOCTYPE html>
<html lang="en-US">
  <head>
  </head>
  <body>
    <button type="button" onclick="addTable()">Add Table</button>
    <button type="button" onclick="removeTable()">Remove Table</button>
  </body>
</html>

JAVASCRIPT CONTENT:

<script language="javascript" type="text/javascript">
 function addTable() {
   var x = document.createElement("table");
   x.id = "table1";
   document.appendChild(x);

   var y = document.createElement("tr");
   x.appendChild(y);

   var z = document.createElement("th");
   z.innerHTML = "FirstName";
   y.appendChild(z);

   var a = document.createElement("tr");
   x.appendChild("a");

   var b = document.createElement("td");
   b.innerHTML("John");
   a.appendChild(b);
 }

 function removeTable() {
   var removeTab = document.getElementById('table1');
   document.removeChild('removeTab');

   // I am not getting the exact syntax to remove the above created table
 }
</script>

Well, in javascript you can't remove directly an element from DOM. You have to go to its parent and remove it from there.

Something like:

var removeTab = document.getElementById('table1').parentElement.removeChild(removeTab);

You can not directly delete a DOM object. You must delete it via it's parent.

var removeTab = document.getElementById('table1');

var parentEl = removeTab.parentElement;

parentEl.removeChild(removeTab);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM