How to Insert a Row in an HTML Table Body in JavaScript

How to insert a row in an HTML table body in JavaScript

If you want to add a row into the tbody, get a reference to it and call its insertRow method.

var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

// Insert a row at the end of table
var newRow = tbodyRef.insertRow();

// Insert a cell at the end of the row
var newCell = newRow.insertCell();

// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>initial row</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My Footer</td>
</tr>
</tfoot>
</table>

Add rows in HTML table with JavaScript

For insert new row in the table, you can use Table insertRow() and insertCell() Methods. The insertRow() methods creates an empty <tr> element and adds it to a table. The insertCell() method inserts a cell into the current row.

See the code below:

function addRows() {  var table = document.getElementById( 'myTable' ),      row = table.insertRow(0),      cell1 = row.insertCell(0),      cell2 = row.insertCell(1);
cell1.innerHTML = 'Cell 1'; cell2.innerHTML = 'Cell 2';}
table {  border: 1px solid #999;  border-collapse: collapse;  width: 100%}td {  border: 1px solid #999}
<p>  <button onclick="addRows()">Add a new row</button></p><table id="myTable"></table>

Using Javascript methods append and appendChild to insert row and cells into a HTML table

You are creating 3 references for a one and same Element in this line:

td_id = td_ba = td_code = td_num = document.createElement('td');

Meaning, the only document.createElement('td') created here can be called with td_id, td_ba and td_code. You are not creating 3 td's here, only one with 3 references.

If you want to create 3 elements you need to create them for every variable

[ td_id, td_ba, td_code ].map(myVarRef => myVarRef = document.createElement('td'))

Add rows to an empty tbody element

you're almost there.

First, as Rory mentioned, you're not targeting the tbody in DOM.
You can fix that by replacing the first line with this:

var body = document.querySelector('#search-table tbody')

What that does, is this: It looks for an element with an ID of search-table and a descendant <tbody> and returns a reference.

Your code would run without an error then, but I'm confused about the result.
In the second line, you have var x = 0 but later on I can see var x = createRow.insertCell(j); also. (The second x would give you a reference to a new <td> element).

Hope that helps.

Inserting dynamic row into HTML table

Steps to Take for Valid HTML and Accurate DOM Manipulation

  1. Remove .render it's incredibly invalid simply because the only child element <table>/<tbody> can have is <tr>.

  2. You probably resorted to using an dive that way because when using .innerHTML the direct logical way ended up obliterating a portion of the table. .innerHTML overwrites whatever it targets unless you use += instead of = which makes .innerHTML append instead overwrite content.

    document.querySelector('table').innerHTML += HTMLString

  3. But there's a method that renders Strings to HTML like .innerHTML but inserts Strings instead overwrites content. Not only is it safer but it's far more accurate.

    .insertAdjacentHTML( position, HTMLString )

    The first parameter, position is one of four possible String, below is represents a target element to which we intend to place a HTMLString (the second parameter) into or around:

    Position: "beforebegin" <table> "afterbegin" ...... "beforeend" </table> "afterend"


Demo

HTMLStr = "<tr><td>GRP2</td><td>1</td><td>Team 3</td><td>32000</td><td>Team 4</td></tr>";

document.querySelector("table").insertAdjacentHTML('beforeend', HTMLStr);
#scrolltable {
margin-top: 20px;
height: 150px;
overflow: auto;
}

#scrolltable table {
border-collapse: collapse;
}

#scrolltable th div {
position: absolute;
margin-top: -20px;
}
<div id="scrolltable"><table><col width="50px"><col width="60px"><col width="120px"><col width="100px"><col width="120px"><tr><th><div></div></th><th><div>Rank</div></th><th><div>Squad Name</div></th><th><div>Skill Pts</div></th><th><div>Current War (vs)</div></th></tr><tr><td>GRP1</td><td>2</td><td>Team A</td><td>30777</td><td>Team B</td></tr></table></div>

Adding rows to table body dynamically

You insert the row into the tBody element. Since there can be more than one tBody, you should refer to the tBodies prop of table at index 0.

var row = tbl.tBodies[0].insertRow(-1);

function test() {  var tbl = document.getElementById("tbl");  var lastRow = tbl.rows.length - 1;  var cols = tbl.rows[lastRow].cells.length;  var row = tbl.tBodies[0].insertRow(-1);  for (var i = 0; i < cols; i++) {    row.insertCell().appendChild(document.createTextNode(i));  }}
test();
<table id="tbl" onclick="test()">  <thead>    <tr>      <th>Month</th>      <th>Savings</th>    </tr>  </thead>  <tfoot>    <tr>      <td>Sum</td>      <td>$180</td>    </tr>  </tfoot>  <tbody>    <tr>      <td>January</td>      <td>$100</td>    </tr>    <tr>      <td>February</td>      <td>$80</td>    </tr>  </tbody></table>

How to use javascript to insert tags in tables

Try this on JSFiddle, it seems to work just fine for me!

// First create a table to be used as an example.
const table = document.getElementById('test-table-1')
const head = document.createElement('thead')

// Create 3 th tags for an example.

const th1 = document.createElement('th')
th1.appendChild(document.createTextNode('Test Header 1'))

const th2 = document.createElement('th')
th2.appendChild(document.createTextNode('Test Header 2'))

const th3 = document.createElement('th')
th3.appendChild(document.createTextNode('Test Header 3'))

// Add the th tags to the thead
head.appendChild(th1)
head.appendChild(th2)
head.appendChild(th3)

// Give the table the thead.
table.appendChild(head)

// Now we have a table to work with.

// Create a tbody.
const tbody = document.createElement('tbody')

// Add a couple of rows.
const tr1 = tbody.insertRow()
const tr2 = tbody.insertRow()

// Add td tags to to rows.
for (let tr of [tr1, tr2]) {
for (let i=0; i<3; i++) {
const td = tr.insertCell(i)
td.innerText = 'foo'+i
}
}

// Add the tbody to the table.
table.appendChild(tbody)
<table id="test-table-1"></table>

Rows are added in thead instead of tbody

check my fiddle here
enter link description here

What you didnt did is to see specifically for tbody. Answered here How to insert row in HTML table body in javascript?

    addButton=document.getElementById("add-button");
table=document.getElementById("data-table");

addButton.addEventListener('click',add,false);

function add()
{

var tableLength=table.length;
var row = table.getElementsByTagName('tbody')[0].insertRow(tableLength);

var col1 = row.insertCell(0);
var col2 = row.insertCell(1);

col1.innerHTML="col1";
col2.innerHTML="col2";
}

var delLink = document.getElementById("delete-link");
delLink.addEventListener('click',del,false);

function del()
{
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});

}


Related Topics



Leave a reply



Submit