Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a childnode to a specific position

How can I append a childNode to a specific position in javascript?

I want to add a childNode to the 3rd position in a div. There are other nodes behind it that need to move backwards (3 becomes 4 etc.)

like image 449
Jarco Avatar asked May 04 '11 11:05

Jarco


People also ask

How does appendChild know where to place an element in a website?

The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

What is difference between append and appendChild?

append() can append several nodes and strings, whereas Node. appendChild() can only append one node.

Can you appendChild to a div?

Use appendChild to Append Data to Div in JavaScript Like the previous method, we first select the div by using one of the selectors. But instead of innerHTML , we use appendChild because of the problems discussed in the previous method. Before appending a child, we have to create the text node.


2 Answers

You can use .insertBefore():

parentElement.insertBefore(newElement, parentElement.children[2]); 
like image 99
Felix Kling Avatar answered Sep 19 '22 17:09

Felix Kling


For this you have 3 options .insertBefore(), .insertAdjacentElement() or .insertAdjacentHtml()


.insertBefore()

var insertedElement = parentElement.insertBefore(newElement, referenceElement); 

in your case you could do as on Felix Kling answer

var insertedElement = parentElement.insertBefore(newElement, parentElement.children[2]); 

.insertAdjacentElement()

referenceElement.insertAdjacentElement (where, newElement); 

in your case it would be

parentElement.children[1].insertAdjacentElement("afterEnd", newElement); 

.insertAdjacentHTML()

referenceElement.insertAdjacentElement (where, newElementHTML); 

in your case it would be

parentElement.children[1].insertAdjacentElement("afterEnd", "<td>newElementHTML</td>"); 
like image 35
MauricioJuanes Avatar answered Sep 17 '22 17:09

MauricioJuanes