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.)
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.
append() can append several nodes and strings, whereas Node. appendChild() can only append one node.
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.
You can use .insertBefore()
:
parentElement.insertBefore(newElement, parentElement.children[2]);
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>");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With