I’m trying to add new row to table which is look’s like this:
<table class="table table-striped">
<tbody id="dconTable">
<th><input type="text" class="span12" id="lbld"></th>
<th><input type="text" class="span12" id="edizmd"></th>
<th><input type="text" class="span12" id="idd"></th>
<th><input type="text" class="span12" id="ad"></th>
<th><input type="text" class="span12" id="bd"></th>
<th><input type="text" class="span12" id="en_spard"></th>
<th><input type="text" class="span12" id="spard"></th>
<th><input type="text" class="span12" id="en_periodd"></th>
<th><input type="text" class="span12" id="periodd"></th>
</tbody>
</table>
I using script which I found on the internet. And I want him also write id’s in new cells (like id=”lbld_1″ etc). Here ‘s the code.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
colName = table.rows[0].cells[i].parentNode.children[1].getAttribute('id') +"_"+ i;
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
newcell.childNodes[0].value = "";
newcell.parentNode.children[1].setAttribute('id',colName);
colName = "";
}
};
Console says:
Uncaught TypeError: Cannot call method 'setAttribute' of undefined
Show me my mistake, please. Thanks.
Your code doesn’t make any sense to me:
cells are children of rows, so get the parentNode of a row, and it’ll return a row, get one of its children and you’re back at the level of the cells (if you’re lucky! – some browsers will include whitespace, or comments in the nodelist).
Besides, if you need an id, just
anElem.idwill do,getAttribute()is a bit much.So this would be what you’re trying to do:
But that’s creating multiple elements with the same ID, which is impossible. In real life, if someone else had my ID, I’d have a problem. Same logic applies to ID’s in the DOM: they are unique! So try:
Lastly, you don’t seem to be appending your elements, so add
table.rows[0].appendChild(newCell);, too