Your Web browser sees an HTML document as a tree of nodes that support properties and methods you can use to navigate or edit that page in real time. Those properties and methods are specified in the HTML Document Object Model, or DOM.
Note | The DOM is the creation of the World Wide Web Consortium (W3C). For the rigorous DOM details, take a look at http://www.w3.org/DOM/. |
For example, here’s the code for an innocent-looking Web page:
<html> <head> <title> Hello from HTML </title> </head> <body> <h1> Hello from HTML! </h1> </body> <html>
Here, everything is a node-from the elements you see to the text (which is stored in text nodes). Following is the tree of nodes corresponding to this Web page that your browser sees:
<html> | --------------------------------- | | | | <head> <body> | | | | <title> <h1> | | | | Hello from HTML Hello from HTML!
JavaScript has built-in properties you can use to work with the nodes in Web documents like this one. They are
attributes: Attributes by this node
childNodes: Array of child nodes
documentElement: The document element
firstChild: First child node
lastChild: Last child node
localName: Local name of the node
name: Name of the node, with namespace
nextSibling: Next sibling node
nodeName: Name of the node
nodeType: Node type
nodeValue: Value of the node
previousSibling: Previous sibling node
You’ll see how to use these properties in JavaScript later in this chapter and in Chapter 9. Note in particular that the nodeType property holds the type of a node, which is given by number in HTML documents:
1 Element
2 Attribute
3 Text node
Here are the various node types in the HTML document you saw earlier:
<html> [Element node] | ----------------------------------- | | | | <head> [Element node] <body> [Element node] | | | | <title> [Element node] <h1> [Element node] | | | | Hello from HTML [Text node] Hello from HTML! [Text node]
Besides these properties, nodes support the following methods:
replaceNode(a, b): Replaces node b with node a
insertBefore(a, b): Inserts node a before node b
appendChild(a): Appends a child, a, to the node that you call this method on.
How do you get a node to work with JavaScript? You can use the documentElement property, which returns the node corresponding to the <html> element, and use properties such as nextSibling, lastChild, firstChild, and so on to navigate to the node you want. Or you can use a method such as document.getElementById to create a node object by accessing elements by ID value.
Now, how about putting this discussion to work in an Ajax example?