JavaScript/Introduction to the Document Object Model (DOM)

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Previous: JavaScript/Runtime Document Manipulation Model Index Next: JavaScript/Finding Elements

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

[edit] Example

<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>

[edit] Explanation

Basically, it rearranges the <div> tag into the <p> tag. Here's how that works:

First, two variables are used and given the values of a DOM function, document.getElementById().

Those variables are given the function with Id values of their respective tags. Variable div finds the first tag with the ID 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 within the value of p. In other words, it puts the div tag inside the p tag.

This Chapter will teach you the basics of DOM and how to use it. Please move on to the next page.


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