Kamala - Nutritional Supplements - Find jobs - Pinnacle Sports Review - Debt Consolidation

PDA

View Full Version : AppendChild after ID


Echilon
Apr 6th 2007, 2:41 am
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>

serjio28
Apr 6th 2007, 3:54 am
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:

Yes you could :)
var div = document.getElementById('child1');
var ndiv = document.createElement('DIV');
if(ndiv && div){
ndiv.innerHTML='child1a';
ndiv.setAttribute('id','child1a');
div.appendChild(ndiv);
};

bibel
Apr 6th 2007, 7:19 am
Wrong !

You need to use appendChild on "container", and then use the childNodes array to position the new div.

I'm not sure it would work, though.

serjio28
Apr 6th 2007, 9:23 am
Wrong !

You need to use appendChild on "container", and then use the childNodes array to position the new div.
I'm not sure it would work, though.

Which browser and OS you used when you got wrong results?
I have tested my code under Mozilla 1.7.8 & Firefox 2.0.0.3 under Linux Debian 3.1
It worked fine for me.
Here the file that I used for the test:

<html>
<head>
</head>
<body>
<div id="container">
container
<div id="child1">child1</div>
<div id="child2">child2</div>
</div>

<script type="text/javascript" language="javascript">
<!--

var div = document.getElementById('child1');
var ndiv = document.createElement('DIV');
if(ndiv && div){
ndiv.innerHTML='child1a';
ndiv.setAttribute('id','child1a');
div.appendChild(ndiv);
};
-->
</script>

</body>
</html>


Really I don't see any issues to refer to child DIV rather then "container" one. In DHTML we can to refer by ID to any element of the page.

Echilon
Apr 6th 2007, 12:35 pm
Thanks Serjio, works perfectly :)


child1 = document.getElementById('child1');
child1a = document.createElement('div');
child1a.id='child1a';
child1.parentNode.insertBefore(child1a,child1.nextSibling);