user3257398
user3257398

Reputation: 43

Append child in DOM table

I am using clone to add new row to the DOM table dynamically from a button click event like below mentioned. but i want to append the cloned node to a specific row position in the DOM table. i know i can do that by using "insertrow" option but i want to use this using clone.

    var newNode = tblBody.rows[1].cloneNode(true); 
    tblBody.appendChild(newNode);

is there any way to insert or append the "newNode" in a position i dynamically choose rather appending it as last row.

Upvotes: 4

Views: 132

Answers (2)

cookie monster
cookie monster

Reputation: 10972

Use .insertBefore() from tblBody, and pass the newNode as teh first argument, and the child of tblBody before which the node should be inserted as the second argument.

    // put this node----v  before this----v
tblBody.insertBefore(newNode, tblBody.rows[i]);

If tblBody.rows[i] is null or undefined, then .insertBefore() will just behave like .appendChild(), and put it at the end.

Upvotes: 4

Munter
Munter

Reputation: 1089

node.insertBefore() is what you are looking for: https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

Upvotes: 0

Related Questions