Entry
How do I use the method insertChildBefore?
How do I use the method insertChildBefore?
Apr 11th, 2005 01:22
Martin Honnen,
The method insertChildBefore takes two arguments, an existing child to
insert before and the new child to be inserted.
If the first argument is null then the child is inserted after all
children as the last child.
If the first argument is an existing child then the second argument is
inserted directly before the first argument.
If the new child is inserted successfully then the XML object the method
is called on is returned, otherwise undefined is returned.
Note that in E4X neither attributes nor text nodes nor comments nor
processing instructions can have child nodes so in this case the method
doees nothing and returns undefined.
Here are some examples:
var gods = <gods>
<god>Kibo</god>
<god>Xibo</god>
</gods>;
// insert at end:
gods.insertChildBefore(null, <god>Maho</god>);
alert(gods);
/* shows
'<gods>
<god>Kibo</god>
<god>Xibo</god>
<god>Maho</god>
</gods>'
*/
// insert before first child
gods.insertChildBefore(gods.*[0], <god>Jaffo</god>);
alert(gods)
/* shows
'<gods>
<god>Jaffo</god>
<god>Kibo</god>
<god>Xibo</god>
<god>Maho</god>
</gods>'
*/
// insertion attempt before not existing child does nothing
var result = gods.insertChildBefore(gods.*[20], <god>Buffo</god>);
alert(result); // shows 'undefined'
alert(gods);
/* shows unchanged
'<gods>
<god>Jaffo</god>
<god>Kibo</god>
<god>Xibo</god>
<god>Maho</god>
</gods>'
*/