Search code examples
javascripthtmlexternal

Loading only just table rows from external javascript file


I am trying to have a table where the headers are there when page loads, but when a user presses a button, I would like to load the rest of the table (the trs and tds of the table) into the myTableInsertRows div, which is coming from an external js file.

<!DOCTYPE html>
<html lang="en">
  <body>
    <div id="container">
    <button onclick="getScript('Insert.js')"> Insert TR/TDs </button> 
    <div id="Table">
      <table id='TableResult1'>
        <th>Color</th>
        <th>Number</th>
        <th>Letter</th>
        <div id="myTableInsertRows"></div> 
       </table>
    </div> 
  </body>
  <script type="text/javascript">
    getScript=(url)=>{
      var script = document.createElement('script');
      script.setAttribute('type', 'text/javascript');
      script.setAttribute('src', url);
      if(document.body == null){
         document.head.appendChild(script);
      }else{
         document.body.appendChild(script);
      }
    }
  </script>

External JS file

var Insert= ' \
<tr><td>Red</td><td>One</td><td>AAAA</td></tr> '
document.getElementById('myTableInsertRows').innerHTML =Insert;

Solution

  • <table id='TableResult1'>
      <thead>
       <tr>
        <th>Color</th>
        <th>Number</th>
        <th>Letter</th>
       </tr>
      </thead>
      <tbody id="myTableInsertRows"></tbody> 
    </table>
    

    You must follow the table structure in which <tr> should be in <tbody> or <thead> tag. I hope this will fix your issue.