Team LiB   Previous Section   Next Section

2.5 The W3C DOM

The W3C DOM standardizes most of the features of the legacy DOM, but also adds important new ones. In addition to supporting forms[ ], images[ ], and other array properties of the Document object, it defines methods that allow scripts to access and manipulate any document element, not just special-purpose elements like forms and images.

2.5.1 Finding elements by ID

When creating a document that contains special elements that will be manipulated by a script, you can identify each special element by giving it an id attribute with a unique value. Then, you can use the getElementById( ) method of the Document object to look up those elements by their ID:

<h1 id="title">Title</h1>  
<script>
var t = document.getElementById("title");
</script>

2.5.2 Finding elements by tag name

Another way to access document elements is to look them up by tag name. The getElementsByTagName( ) method of the Document object returns an array of all elements of that type. Each document element also supports the same method, so you can also obtain an array of specific types of tags that are all descendents of an element:

// Get an array of all <ul> tags
var lists = document.getElementsByTagName("ul");
// Find the 3rd <li> tag in the second <ul>
var item = lists[1].getElementsByTagName("li")[2];

2.5.3 Traversing a document tree

The W3C DOM represents every document as a tree. The nodes of this tree represent the HTML tags, the strings of text, and the HTML comments that comprise the document. Each node of the tree is represented by a JavaScript object, and each has properties that allow you to traverse the tree, as illustrated by the following code fragment:

// Look up a node in the document
var n = document.getElementById("mynode");
var p = n.parentNode;  // The containing tag
var c0 = n.firstChild;    // First child of n
var c1 = c0.nextSibling;  // 2nd child of n
var c2 = n.childNodes[2]; // 3rd child of n
var last = n.lastChild;   // last child of n

See Node in the reference section for further details.

The Document object itself is a kind of node, and supports these same properties. The documentElement property of the Document object refers to the single <html> tag element at the root of all HTML documents, and the body property refers to the <body> tag.

2.5.4 Node types

Every node in a document tree has a nodeType property that specifies what type of node it is. Different types of nodes are represented by different subclasses of the Node object. The following nodeType values are relevant to JavaScript programmers working with HTML documents (other values exist for XML documents):

nodeType

Represents

1

Element: an HTML tag

2

Text: text in a document

8

Comment: an HTML comment

9

Document: the HTML document

Use the nodeName property of an Element node to determine the name of the HTML tag it represents. Use the nodeValue property of Text and Comment nodes to obtain the document text or comment text represented by the node. See Element, Text, Comment, and Document in the reference section for details on each of these node types. Also see Node for information on the common properties and methods they all share.

2.5.5 HTML attributes

As we've seen above, HTML tags in a document tree are represented by Element objects. In HTML documents, each Element object has properties that correspond directly to the attributes of the HTML tag. For example, you can query or set the value of the caption attribute of a <table> tag by setting the caption property of the corresponding Element object. See Element in the reference section for details.

2.5.6 Manipulating document elements

One easy way to manipulate HTML documents with the W3C DOM is simply to set the properties that correspond to HTML attributes. As we saw in the legacy DOM, this allows you to change images by setting the src property of the document element that represents an <img> tag, for example. It also allows you to set colors, sizes, and alignments of document elements. One particularly fruitful way to manipulate document elements is through the style property which controls CSS styles. We'll cover this important topic in more detail later.

2.5.7 Changing document text

You can change the textual content of a document simply by setting the nodeValue property of a Text node:

// Find the first <h1> tag in the document
var h1 = document.getElementsByTagName("h1")[0];
// Set new text of its first child
h1.firstChild.nodeValue = "New heading";

In addition to manipulating the nodeValue property, the Text object also allows you to modify the data property, or to use methods to append, insert, delete or replace text.

Note that the problem with the previous code is that it assumes that the content of the <h1> tag is plain text. The code would fail for a document with the following heading because the text of the heading is a grandchild of the <h1> tag rather than a direct child:

<h1><i>Original Heading</i></h1>

One way around this problem is to set the innerHTML property of the heading node. This property is part of the IE 4 DOM, not the W3C DOM, but it is supported by most modern browsers because it is so useful. We'll see it again when we consider the IE 4 DOM. Another way around the problem is to replace the heading node with a newly created <h1> tag and text node containing the desired text, as shown in the next section.

2.5.8 Changing document structure

In addition to changing document text and the attributes of document elements, the W3C DOM allows you to alter the tree structure of the document itself. This is done with Node methods that allow you to insert, append, remove, and replace children of a node and with Document methods that allow you to create new Element and Text nodes. The following code illustrates:

// Find a <ol> element by name:
var list = document.getElementById("mylist");
// Create a new <li> element
var item = document.createElement("li");
// Append it to the list
list.appendChild(item);
// Create a Text node
var text = document.createTextNode("new item");
// Append it to the new <li> node
item.appendChild(text);
// Remove the new item from the list
list.removeChild(item);
// Place the new item at the start of the list
list.insertBefore(item,list.firstChild);

As a further example, here is a JavaScript function that uses the W3C DOM to embolden an arbitrary document node by reparenting it within a newly created <b> tag:

function embolden(node) {  // Embolden node n
  var b = document.createElement("b");
  var p = n.parentNode; // Get parent of n
  p.replaceChild(b, n); // Replace n with <b> 
  b.appendChild(n);     // Insert n into <b> tag
}
    Team LiB   Previous Section   Next Section