Reputation: 317
I want to add a new child node, after a specified node, as the third child node.
<ul id="menu">
<li>one</li>
<li>tow</li>
<li>three</li>
<li>four</li>
</ul>
<script>
var li = document.createElement("li");
document.getElementById("menu").appendChild(li);
var sometext = document.createTextNode("third one");
li.appendChild(sometext);
</script>
Upvotes: 2
Views: 3574
Reputation: 477
keep in mind that there is a difference in childNodes
, namely siblings
and ElementSiblings
. a textNode
is a Node
, but not an Element
. so if you want to insert an element into the the DOM, use nextElementSibling
| previousElementSibling
and appendChild
| insertBefore
and the parent's children
attribute that only contains Elements like this:
function insertAsThird( element, parent ){
if ( parent.children.length > 2 ){
parent.insertBefore(element, parent.children[2]);
}
else parent.appendChild(element);
}
and use it like this:
insertAsThird( yourThirdElement, document.getElementById("your target parent"));
if you want to to work on childNodes, not Elements, just change the parent.children
parts to parent.childNodes
Upvotes: 4
Reputation: 1643
javascript (without jQuery):
var newLi = document.createElement("li");
newLi.innerHTML ="new el 3"
var menu = document.getElementById("menu");
var el3 = menu.getElementsByTagName("li")[2];
menu.insertBefore(newLi, el3);
or with jQuery:
$('#menu').children().eq(1).append('<li>new</li>');
Upvotes: 1
Reputation: 36
I think you should append the textNode before adding the new element like this:
<script>
var li = document.createElement("LI");
var sometext = document.createTextNode("third one");
li.appendChild(sometext);
var menu = document.getElementById("menu");
var third = parent.getElementsByTagName("LI")[2];
menu.insertBefore(li, third);
</script>
I Hope this works for you..
Upvotes: 1
Reputation: 943108
Use insertBefore
if you want to add a node anywhere before the end of its container.
parentElement.insertBefore(newNode, currentThirdNode);
Upvotes: 5