Walking the DOM Tree

CSE 190 M (Web Programming), Spring 2008

University of Washington

References: Forbes/Steele, Chipman (much of this content was stolen from them)

Except where otherwise noted, the contents of this presentation are © Copyright 2008 Marty Stepp and Jessica Miller and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.1 Valid CSS!

Lecture Outline

An example XHTML page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
<html xmlns="http://www.w3.org/1999/XHTML"> 
		<title>Page Title</title> 
		<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 

		<h1>This is a heading</h1>
		<p>A paragraph with a <a href="http://www.google.com/">link</a>.</p>
			<li>a list item</li>
			<li>another list item</li>
			<li>a third list item</li>

The resulting DOM tree

DOM tree

Types of nodes

<p>This is a paragraph of text with a 
	<a href="/path/to/another/page.html">link</a> inside.</p>
DOM Tree

Traversing the DOM tree

every node's DOM object has the following properties:

DOM tree traversal example

<p id="foo">This is a paragraph of text with a 
	<a href="/path/to/another/page.html">link</a> inside.</p>

navigate tree

Annoying text nodes

<div id="foo">
		This is a paragraph of text with a 
		<a href="page.html">link</a>

Prototype DOM tree traversal methods

All of the following methods return only element nodes (not text nodes):


set all siblings of the element with id of main to be bold:

var siblings = $("main").siblings();
for (var i = 0; i < siblings.length; i++) {
	siblings[i].style.fontWeight = "bold";

Modifying the text inside a node

$("foo").textContent = "New paragraph text";  // change text on the page

Abuse of innerHTML

// bad style!
$("foo").innerHTML = "<p>text and <a href="page.html">link</a>";

Creating new nodes

// create a new <h2> node
var newHeading = document.createElement("h2");
newHeading.style.color = "green";
newHeading.textContent = "This is a heading";

Adding a node to the page

window.onload = function() {
	$("thisslide").onclick = slideClick;

function slideClick() {
	var p = document.createElement("p");
	p.textContent = "A paragraph!";

Modifying the DOM tree

Every DOM node object has these methods:

DOM versus innerHTML revisited

Why not just code the previous example this way?

function slideClick() {
	$("thisslide").innerHTML += "<p>A paragraph!</p>";

Ugly innerHTML code

Imagine that the new node is more complex:

function slideClick() {
	this.innerHTML += "<p style='color: red; " +
			"margin-left: 50px;' " +
			"onclick='myOnClick();'>" +
			"A paragraph!</p>";

Benefits of DOM over innerHTML

function slideClick() {
	var p = document.createElement("p");
	p.style.color = "red";
	p.style.marginLeft = "50px";
	p.onclick = myOnClick;
	p.textContent = "A paragraph!";

Practice problem: Rectangles

Click a rectangle to move it to the front. Shift-click a rectangle to delete it.