Inserting Elements With the += Operator

Using the += operator, you can insert an XML element at the end of a list of sibling elements. (Note that this operator is equivalent to using the appendChild function described in Functions for Manipulating XML.)

This can be useful when you want to insert a new element into an existing list, as in the following example.

/* Declare an XML variable with a literal XML value. */
var xmlEmployees =
    <employees>
        <employee>
            <firstname>John</firstname>
            <lastname>Walton</lastname>
            <age>25</age>
        </employee>
        <employee>
            <firstname>Gladys</firstname>
            <lastname>Cravits</lastname>
            <age>53</age>
        </employee>
</employees>;

/* Insert a new node with information about Rob Petrie at the end of the list */
xmlEmployees..employee[1] += 
        <employee id = "333333333">
            <firstname>Rob</firstname>
            <lastname>Petrie</lastname>
            <age>34</age>
        </employee>;

This operator can't be used in cases where the left operand is an XMLList, as in the following example. This example attempts to insert the new <employee> element at the end of the list by omitting a specific reference to a particular element (as in the preceding example). To insert an element as the last in a list, use the appendChild function.

/* This causes a run-time error. */
xmlEmployees.employee += 
        <employee>
            <firstname>Sue</firstname>
            <lastname>Day</lastname>
            <age>32</age>
        </employee>;

Related Topics

appendChild function