Main Page

resulting XML

var oXml = <employees>
<employee position=”Software Engineer”>
<name>Nicholas C. Zakas</name>
</employee>
<employee position=”Salesperson”>
<name>Jim Smith</name>
</employee>
</employees>;
var oFirstEmployee = oXml.child(0);
var oFirstEmployeeToo = oXml.child(“employee”);
var oAllEmployees = oXml.children();
var iFirstEmployeeIndex = oFirstEmployee.childIndex(); //0
This code shows two ways of obtaining the first employee in the XML code. First, the
child()
method
is used with the position
0
, the location of the first element. Then, the
child()
method is used with the
tag name of the element. Each of these calls returns a reference to the same employee element. To get all
employees, the
children()
method is called. Finally, the first employee’s
childIndex()
method is
called, which returns
0
.
The methods discussed previously return all types of child nodes for the given element. However, if you
want to return only child nodes of a specific type or nodes that relate to the element in different ways,
several methods are available:
?
comments()
— Returns only comment child nodes
?
elements()
— Returns only element child nodes
?
processingInstructions()
— Returns only processing instruction child nodes
?
descendants()
— Returns all nodes that descend from the given element
?
parent()
— Returns the parent node of the element
A variety of methods are available to alter child nodes:
?
appendChild(
child
)
— Adds a new child to the end of the children
?
prependChild(
child
)
— Adds a new child to the beginning of the children
?
insertChildBefore(
child
,
refchild
)
— Inserts a child before a given reference node
?
insertChildAfter(
child
,
refchild
)
— Inserts a child after a given reference node
?
replace(
childname
,
newchild
)
— Replaces the child with the given name (or position)
with a new child
?
setChildren(
list
)
— Replaces all children with children contained in a given
XMLList
These methods are incredibly useful and easy to use:
var oXml = <employees>
<employee position=”Software Engineer”>
<name>Nicholas C. Zakas</name>
</employee>
<employee position=”Salesperson”>
<name>Jim Smith</name>
611
The Evolution of JavaScript
23_579088 ch20.qxd 3/28/05 11:44 AM Page 611


JavaScript EditorFree JavaScript Editor     Ajax Editor


©