Forum Moderators: open

Message Too Old, No Replies

AppendChild after ID

         

Echil0n

9:47 am on Apr 6, 2007 (gmt 0)

10+ Year Member



I have a div containing a few elements. Is it possible to append a child after an element with a certain ID?
Eg:
<div id="container>
<div id="child1"></div>
<div id="child2"></div>
</div>

Could I append a child after child1, to give:
<div id="container>
<div id="child1"></div>
<div id="child1a"></div>
<div id="child2"></div>
</div>

Dabrowski

10:45 am on Apr 6, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You have to use divContainer.insertBefore( newNode, divChild2)
You'd have to fine the childNode index of the node you wanted it after, and use the next one, but ONLY if it wasn't already the last one. Otherwise use divContainer.appendChild.

Should be quite easy to knock up.

Fotiman

2:35 pm on Apr 6, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



They really should have added this as a DOM method. But since they didn't:


function insertAfter(newChild, refChild) {
refChild.parentNode.insertBefore(newChild,refChild.nextSibling);
}

That will work regardless of whether the refChild has any other siblings after it or not.

Dabrowski

2:47 pm on Apr 6, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks Fotiman, I'll remember that one too.