2

I wrote a script which contain two tables: tbl1 is a main table, tbl2 is a second table which I want to insert into a tbl1 second row by using Pure JavaScript. It work perfectly, but my tbl2 have some html attribute, it doesn't seen when i saw the code after inserted
note: tbl1 and tbl2 both are same column header and there have two columns.

function inserttbl2() {
    var table = document.getElementById("tbl1");
    var row = table.insertRow(1);
    var celltr = row.insertCell(0);
    row.innerHTML = document.getElementById("tbl2").outerHTML;
}
.myclass{
background-color: green;
color: white;
}
<!DOCTYPE html>
<html>

<body>

<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>

<table id="tbl1">
  <tr>
    <td>table 1</td>
    <td>table 1</td>
  </tr>
  <tr>
    <td>table 1</td>
    <td>table 1</td>
  </tr>
</table>

<br />
<button onclick="inserttbl2()">Insert</button>
<br />

<table id='tbl2' class='myclass'>
<tr>
<td>table 2</td>
<td>table 2</td>
</tr>
</table>

</body>
</html>

As you see, the tbl2 doesn't have a <table id=....>

enter image description here

Aso
  • 603
  • 7
  • 16

1 Answers1

2

You can use the regular appendChild for your case, like this:

function inserttbl2() {
    var table = document.getElementById("tbl1");
    var row = table.insertRow(1);
    var celltr = row.insertCell(0);
    row.appendChild(document.getElementById("tbl2"));
}
.myclass{
background-color: green;
color: white;
}
<!DOCTYPE html>
<html>

<body>

<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>

<table id="tbl1">
  <tr>
    <td>table 1</td>
    <td>table 1</td>
  </tr>
  <tr>
    <td>table 1</td>
    <td>table 1</td>
  </tr>
</table>

<br />
<button onclick="inserttbl2()">Insert</button>
<br />

<table id='tbl2' class='myclass'>
<tr>
<td>table 2</td>
<td>table 2</td>
</tr>
</table>

</body>
</html>

It will insert full second table inside the first.

P.S.
  • 15,970
  • 14
  • 62
  • 86
  • the tbl2 in your answer is no't a right position sir, can you sent tbl2 into a div then insert into tbl1 please ? – Aso Nov 04 '17 at 15:31