Visual Hierarchy in JavaScript
The Document Object Model makes it possible for Web pages to appear in your browser. The DOM consists of objects that describe items you can place in an HTML document. These objects exist in a visual hierarchy similar to one you might find in an organization chart or in a tree view like the one that displays folders in Windows Explorer. By understanding the DOM, you can use JavaScript to build powerful interactive applications using JavaScript.
-
DOM Objects
-
In an organization chart, a single item such as the CEO text box may appear at the top. In the HTML DOM, the top-level object is the Window. This is the window you see when you open a Web page. The Window object contains child objects such as Location and History. The History object, for instance, keeps track of sites you visit. Draw this visual hierarchy on paper, and the Window appears at the top of the page; the History and Location objects appear as children of the Window object.
Document Object
-
As a developer or user, you will probably spend a lot of time managing and viewing the Document Object. Another child of the Window object, the Document Object contains the items you see on a Web page. This includes links, images and forms. Each of these objects can have child objects and nodes. The Form object, for example, contains Text nodes. Any text that you see on a Web page resides in a Text node.
-
Accessing the DOM
-
Consider the following HTML code that places a paragraph on a Web page.
<p id="paragraph1">My Paragraph</p>
This paragraph, defined using the <p> tag, is a node in the DOM hierarchy tree. The paragraph also contains a text node that contains the words, "My Paragraph." Because the DOM allows you to access anything, you can use JavaScript to change the paragraph's text by finding the paragraph node and updating its text node. The code shown below demonstrates this.
document.getElementById('paragraph1').firstChild.nodeValue='New Text';
The getElementById function retrieves a reference to the paragraph from the Document object. The code then accesses the paragraph's firstChild attribute and changes its nodeValue to "New Text."
Advanced DOM Scripting
-
You also have the ability to delete existing DOM objects and create new ones as shown below.
var newHeading = document.createElement("h2");
newText = document.createTextNode("New Text");
newHeading.appendChild(newText);
document.body.appendChild(newHeading);This code generates a new heading and a new text node. It then appends the new heading to the Document object. This ability comes in handy when you need to create special effects or simply add new Web page functionality as site visitors use your application. Because the HTML Head element is an object, you can even create new script tags that link to external JavaScript files.
-
References
Resources
- Photo Credit Christopher Robbins/Photodisc/Getty Images