JavaScript/Introduction to the Document Object Model (DOM)

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: JavaScript/Runtime Document Manipulation Index Next: JavaScript/Finding Elements

The Document-Object Model, or DOM, is one of JavaScript's more powerful uses. With DOM, you can navigate through and modify an entire page, ranging from simply adding an element to rearranging several areas on the page.

Nodes[edit]

DOM breaks up a document into a tree of nodes. For example, take a look at the following HTML snippet:

<div id="exampleDiv">This is an<br>example HTML snippet.</div>

Through DOM, JavaScript sees this snippet as four nodes. The div, from its start tag through its end tag, is one node. This div happens to have a property assigned inside its start tag. This property is named "id" and has the value "exampleDiv".

The three other nodes in this example are inside the div. They are called child nodes of the div, because the div encompasses them. Conversely, the div is their parent node. The first child of the div is a text node, with the value "This is an". Text nodes contain only text; they never contain tags, which is why the node stops here. The <br> tag is another node, and the rest of the text is another text node. Since the text nodes and the <br> tag all share the same parent, they are said to be sibling nodes.

Example[edit]

<html>
<head>
</head>
<body>
<p id="DOMEx"></p>
<div id="DOMExample"></div>
<script type="text/javascript">
var div=document.getElementById("DOMExample"); // Finds the div above
var p=document.getElementById("DOMEx"); // Find the p above
p.appendChild(div);
</script>
</body>
</html>

What the above example would do would be similar to the following:

<html>
<head>
</head>
<body>
<p id="DOMEx"><div id="DOMExample"></div></p>
</body>
</html>

Explanation[edit]

This code rearranges the HTML, moving the <div> tag from a sibling of the <p> tag to its child. Here's how that works:

First, the two nodes are found by the use of the DOM function document.getElementById(). The nodes are assigned to two variables. Variable div finds the first tag with the ID property DOMExample. Variable p finds the first tag with the ID DOMEx, which, in this example, is the <p> tag.

p.appendChild() uses the appendChild function to place the value of div under the node associated with p, as its last child. In other words, it puts the div tag inside the p tag.

Previous: JavaScript/Runtime Document Manipulation Index Next: JavaScript/Finding Elements