Entry
How do I insert a child element into the existing child elements of an XML object representing an element?
How do I insert a child element into the existing child elements of an XML object representing an element?
Apr 30th, 2005 03:07
Martin Honnen,
If you want to insert a new child element you can use the += operator to
append the new child at a certain position e.g.
xmlElementObject.someChild[index] +=
<new-element>content</new-element>
Here are some examples:
var gods = <gods>
<god>Kibo</god>
<god>Xibo</god>
</gods>;
// insert after first god:
gods.god[0] += <god>Jaffo</god>;
alert(gods);
/* shows
'<gods>
<god>Kibo</god>
<god>Jaffo</god>
<god>Xibo</god>
</gods>'
*/
// insert after second god:
gods.god[1] += <god>Maho</god>;
alert(gods);
/* shows
'<gods>
<god>Kibo</god>
<god>Jaffo</god>
<god>Maho</god>
<god>Xibo</god>
</gods>'
*/
If you want to insert before the first child then you need to use
xmlElementObject.*[0] =
<new-element>content</new-element> + xmlElementObject.*[0];
Here are some examples:
var gods = <gods>
<god>Kibo</god>
<god>Xibo</god>
</gods>;
// insert before first god:
gods.god[0] = <god>Jaffo</god> + gods.god[0];
alert(gods);
/* shows
'<gods>
<god>Jaffo</god>
<god>Kibo</god>
<god>Xibo</god>
</gods>'
*/
var html = <div xml:lang="en">
<h1>Kibology for all</h1>
<p>All for Kibology. Kibology for all.</p>
</div>;
// insert before first child
html.*[0] = <h1>All for Kibology</h1> + html.*[0];
alert(html);
/* shows
'<div xml:lang="en">
<h1>All for Kibology</h1>
<h1>Kibology for all</h1>
<p>All for Kibology. Kibology for all.</p>
</div>'
*/
If you want to insert a new child as the last child then you can simply
add to element.* e.g.
xmlElementObject.* += <new-element>content</new-element>
Here are some examples:
var html = <div xml:lang="en">
<h1>Kibology for all</h1>
<p>Kibology for all. All for Kibology. </p>
</div>;
// insert new child as last child
html.* += <h1>All for Kibology</h1>;
alert(html);
/* shows
'<div xml:lang="en">
<h1>Kibology for all</h1>
<p>Kibology for all. All for Kibology.</p>
<h1>All for Kibology</h1>
</div>'
*/