I have an HTML Table consisting of several rows. I am trying to insert rows at a specific position in the table. For example if I mark an already existing row and click insert a new row should be inserted below. At the moment adding rows at the bottom of the table works. What I need is to insert the already build row at a certain position.
Here is my code:
function addLine(lineNumberGlobal,columnnumber,insertion)
{
var newrow = document.createElement("tr");
newrow.setAttribute('id', globalObj.lineNumberGlobal);
newrow.setAttribute('onmousedown', "setCurIdG(getAttribute(\"id\"))");
for (j = 1; j <= globalObj.monthdays + 1; j++)
{
//build row cells with content
}
if (insertion == true)
{
var newrowinsert = globalObj.bodyGlobal.insertRow(globalObj.currenIdGlobal);
//this actually inserts a new empty row but I want to append my existing row "newrow"
}
else if (insertion == false)
{
globalObj.bodyGlobal.appendChild(newrow);
}
}
Any help would be appreciated …
You can use the
insertBeforeDOM method. If you want to insert after the row that you have marked, you would need to use that row’snextSiblingto find the row after it, and then insert before that.If I assume that
globalObj.currenIdGlobalis the ID of the row you want to insert after, that would look like this:That assumes that your HTML is structured with no whitespace or similar between rows (since
nextSiblingwill return the next node after the row, which can be a text node rather than an element). If you need to be more defensive:and then change the above to:
Note that if you pass
nullas the second argument toinsertBefore, it appends to the end.FWIW, operations like these can be made a bit easier if you use a library like Prototype, jQuery, Closure, or any of several others.