Search code examples
javascripthtmlgetelementsbytagname

Insert tables into div via JavaScript


Hello I'm trying to insert multiple tables into a div.

I have a multiple tables in my document for e.g.

<table>
   <tr>
      <th>1</th>
      <th>2</th> 
   </tr>
   <tr>
      <td>1</td>
      <td>2</td>
   </tr>
</table>

Now I want to select them:

table = document.getElementsByTagName("TABLE");

create div with class "tablediv"

and add each table to "tablediv" like:

<div class="tablediv">
   <table>
      ...
   </table>
</div>

Is it possible with pure js?


Solution

  • You could do something like this:

    let divTable = document.createElement("div"); //create new <div>
    divTable.id = "tablediv";
    
    let tables = document.getElementsByTagName("table"); //HTMLCollection which is live, no need to delete "old tables"
    while (tables.length > 0) divTable.append(tables[0]); //add every <table> to the new <div>
    
    let body = document.querySelector("body"); //change to the preferred selector
    body.append(divTable); //append new <div> to the selected Element, in this case <body>