Home > Articles

Manipulating Documents: The Document Object Model (DOM)

This chapter is from the book

This chapter is from the book

You will learn about the following in this chapter:

  • The various DOM Recommendations

  • The difference between elements and nodes

  • The DOM API and what it represents

  • Navigating the DOM tree

  • Creating a DOM document from a file

  • Creating and manipulating DOM data

  • Saving a DOM document to a file

When new XML users go to the W3C site (http://www.w3.org) and look up the Document Object Model (DOM), very often they're overwhelmed from the start. This is not surprising; there are three different levels, each of which has separate recommendations (or modules). So what is it that you're actually supposed to do with this stuff?

Simply put, the Document Object Model is a way of looking at a tree of XML data, and a group of APIs for reading and manipulating it. These APIs are common among DOM-compliant applications, so what works in one environment should work in another.

Your software determines the version of DOM available to you. At the time of this writing, most implementations (but not all) are at Level 2.0, with some support for Level 3.0. In most cases, you'll use the Core module, but there are situations in which each of the other modules will be useful.

This chapter provides an overview of all the recommendations, and focuses on the DOM Level 2.0 Core. In Chapter 4, "Advanced DOM Techniques," and Chapter 13, "XML in the Browser: XHTML," we'll look at some of the other modules.

What Is the Document Object Model?

The Document Object Model actually sprang out of browsers scripting HTML pages. Back when this sort of scripting (now known as DHTML, or Dynamic HTML) was new, each browser implemented it in its own way. For example, thinking of a form as an object was a fairly obvious choice, but how would you represent the value of a form input called username? Would it be one of the following?


The list wasn't exactly endless, and some of these choices were functionally equivalent, but there were enough differences in what was supported between different browsers (and even versions of the same browser) to cause a nightmare for Web developers who needed to make sure their pages worked everywhere that scripting was available.

The result was the development of the Document Object Model, a (sort-of) standard way of looking at HTML. This unofficial version, based on version 3.x browsers, is known as DOM Level 0.

The first official version, DOM Level 1.0, created a basic structure of nodes, elements, and attributes that allowed navigation around a document. Even from the beginning, however, everyone knew that this was just a starting point, and since then DOM Level 2.0, which incorporates more functionality, has been (mostly) approved, and DOM Level 3.0, which takes things a step further, is in the works.

As I said before, it's easy to get confused with all these recommendations. Let's start simple, with the Core Recommendation.

A Set of Interfaces

In some ways, it's misleading to say that the Document Object Model defines a set of objects. Actually, it defines a set of interfaces to objects. An interface is a set of the following:

  • Properties or data that an object holds

  • Methods or actions that an object can take

  • Parameters that you can pass to an object or method

  • The type of object that a method returns, if any

A programmer can implement these interfaces by creating objects that conform to them. This way, when another programmer wants to use these objects, he or she will know how, because they're based on these well-defined interfaces.

For example, the DOM Core Recommendation defines an interface called Element, with a method called getAttribute(). The interface specifies that when the getAttribute() method is called with the name of an attribute, it should return the value of the attribute. This means that if I create an object based on this Element interface, you can use it secure in the knowledge that if you want the value of an attribute, you can use the getAttribute() method.

Because the interfaces are standard, the implementation itself takes on less importance. All you care about is that if you call getAttribute("month") on the birthday element, you're going to get the value of the month attribute. This portability is the purpose of the Document Object Model.

The Importance of Nodes

When you come right down to it, all of DOM is based on the node. Documents, elements, attributes, text, and even processing instructions and comments are all special cases of the Node interface.

For example, the XML document

<?xml version="1.0"?>
  <handle degree="close">Harold</handle>

actually represents at least 8 nodes of different types:

  • one document node

  • two element nodes (friend and handle)

  • four text nodes (close, Harold, and the line feeds before and after the name element)

  • one attribute node (degree)

These nodes are arranged in parent-child relationships, as shown in Figure 3.1.

Figure 3.1Figure 3.1 The parent-child relationships of a simple document.

Notice that the elements and the text they contain are separate nodes; the element node acts as the parent and the text node as the child, as indicated by the arrows. Notice also that the attribute node is not a child of the element node.

The Document Object Model defines 12 different node types, each of which implements the Node interface, and each of which adds methods that are peculiar to itself.

For example, the Node interface specifies the getNodeValue() method, because it's applicable to most node types. The getTarget() method, on the other hand, applies only to processing instructions, and as such is part of the ProcessingInstruction interface.

The Document Object Model specifies the following interfaces:

  • Node—The overall type that applies to everything. The Node interface includes methods for getting information about the Node, such as getParentNode() and getNodeName(), and for manipulating the structure of a document or individual node, such as insertBefore() and removeChild(). It also defines numeric values for each node type, enabling you to determine what type of node you're dealing with even if the object type itself is Node.

  • Document—The Node that begets almost all other types of nodes. While the Node interface carries the methods that are used to move nodes around, the Document interface carries the methods that are used to actually create them, such as createElement() and createTextNode().

  • Element—The type of node that can be associated with Attr nodes. This interface contains convenience methods such as getElementsByTagName().

  • Attr—This node, whose name is short for attribute, can have either Text nodes or EntityReferences as children.

  • Text—This is a string with no markup. This means that a mixed-content text node is broken up into separate Text and Element nodes.

  • CDATASection—This node type "hides" markup. Unlike a Text node, markup within the value will not cause a separate Element node to be created.

  • DocumentType—This node type contains all the information that would normally be contained in the internal subset of a DTD as a string value. It also contains the name of the specified root element and any system or public identifiers that point to external subsets of the DTD.

  • Comment, Notation, Entity, EntityReference, and ProcessingInstruction—These nodes simply model their namesakes, providing the appropriate information about themselves.


We'll deal with entities, entity references, and notations in detail in Chapter 7, "Document Type Definitions (DTDs)."

Some DOM interfaces don't correspond to actual node types within the document, but are provided to make your life easier when you're working with documents:

  • DocumentFragment—This implementation of the Node interface doesn't actually have any of its own methods at all, and instead acts as a sort of mini-document or container for other groups of nodes you may want to move around. For example, if you insert a DocumentFragment into a document, only the child nodes are actually inserted.

  • DOMImplementation—This interface provides a means to determine whether certain actions are supported using the hasFeature() method. It also allows you to create Documents and DocumentTypes.

  • DOMException and ExceptionCode—These interfaces provide a way for the application to tell you that something has gone wrong, and what it is.

  • NodeList and NamedNodeMap—These two utility interfaces are essential in actually working with a DOM document, as you'll see when we start building the application. NodeList provides an ordered list of results, such as the children of a node, and NamedNodeMap provides a list that is unordered but accessible by name, such as the attributes of an element.

The Different Recommendations

All these interfaces are part of the DOM Level 1.0 Recommendation. Minor changes were made to Level 1.0 to create the DOM Level 2.0 Core Recommendation.

DOM Level 2.0 includes five other module recommendations, each of which has a specific purpose:

  • DOM Level 2.0 Traversal and Range—This module includes two new interfaces, NodeIterator and TreeWalker, that provide alternative means for navigating the document. It also defines a means for referring to a particular portion of a document. (We'll talk about ranges in Chapter 14, "XML Linking Language (XLink)."

  • DOM Level 2.0 HTML—This module includes specialized versions of the definitions in the Core Recommendation, such as HTMLDocument and HTMLFormElement. These interfaces are most commonly implemented in a browser, where JavaScript or other client-side scripting controls an HTML page.

  • DOM Level 2.0 Style Sheets—This module specifies interfaces that deal with cascading style sheets and the data they contain.

  • DOM Level 2.0 Views—This module provides a way to distinguish between different versions of a document. For example, a cascading style sheet may change the data within a document, creating a different view. (As of the time of this writing, this module has been removed from DOM Level 3.0.)

  • DOM Level 2.0 Events—This module stems from work on browser scripting, and provides a way to determine the behavior of objects when some action, such as a mouse click, affects them, their ancestors, or their descendants.

DOM Level 3.0, which is still in the Working Draft stage at the time of this writing, includes revisions of the Core and Events modules, as well as two new modules:

  • DOM Level 3.0 Load and Save—This module attempts to actually detail the loading and saving of documents (which is, as of Level 2.0, still up to the individual implementers).

  • DOM Level 3.0 Validation—This module provides a way to validate an existing Document object against a specific associated grammar, and to require that it remain valid throughout its existence.

  • DOM Level 3.0 XPath—This module allows greater flexibility in the use of XPath expressions to locate and specify nodes within a document. It's not an update of XPath, but rather a way to use XPath 1.0 with a DOM document.

Determining Support

So with all these different versions and implementations and modules, how do you know whether a particular method or interface is available for your application?

The answer lies in the DOMImplementation interface and its hasFeature() method. Each of these modules has a standard name and version, so to determine whether the TreeWalker interface is available, you can check the following value:

myDOMImplementation.hasFeature("Traversal", "2.0")

We'll see an example of this in the next section, once we've actually created a DOM document to work with.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020