The Document Object


The Document object represents the complete XML document. It inherits from the Node object class. This is the only interface that allows you to create the other objects that can be found only inside documents.

Table 16.9 shows the properties of the Document object.

Table 16.9 Document Object Attributes/Properties

Name Value

documentElement The root Element object of the document
doctype DocumentType object (defined in the extended interfaces)

Listing 16.10 shows a JavaScript example for getting the root element of an XML document.

Listing 16.10 Getting the Root Element of an XML Document


1:  //var xml holds the xml document
2:  var docRoot = xml.documentElement;
3:  return "The root element is " + docRoot.nodeName + " element.";
4:  //the nodeName property returns the tag name of the element

Table 16.10 shows the methods of the Document object.

Table 16.10 Document Object Methods

Name Returns

createElement(tagName) A new Element object named tagname (string)
createTextNode(data) A new text node with the specified data (string)
createComment(data) A new comment with the specified data (string)
getElementsByTagName(tagname) A NodeList of all descendant elements with the given tagname (string)



Listing 16.11 shows a JavaScript example for creating a new element in an XML document.

Listing 16.11 Creating an Element


1:  //var xml holds the XML document object
2:  var newElement = xml.createElement("remark");

This method does not make the node part of the document tree. The insertBefore or appendChild methods of the Node object can be used for that purpose.