The Document Object Model (DOM)

R. Alexander Miłowski

milowski@ischool.berkeley.edu

School of Information, UC Berkeley

What is the Document Object Model (DOM)

An API and set of behaviors for traversing and manipulating XML and HTML documents.

document.documentElement
var mystuff = document.getElementById("mystuff");
mystuff.innerHTML = "<p>Hello World!</p>";
mystuff.firstChild.appendChild(document.createTextNode(" Cruel, cruel, world!");
         

Check your browser against these specifications!

Basics

What is the textContent of ?

What is the ? It's a trick question.

NodeLists

for (var i=0; i<nl.length; i++) {
   var n = nl[i];
}

// is equivalent to

for (var i=0; i<nl.length; i++) {
   var n = nl.item(i);
}
         

Modifying Style

Everything you ever wanted to know and then some...

How would you turn this sentence ? or ? or ?

Creating Content

Basic Rules:

  1. You can't have a node in two places.
  2. Use node.cloneNode(true) to make a copy.
  3. You can't just insert nodes from other documents without making a copy.
  4. Every little bit must be created separately and that is tedious.
  5. innerHTML is very helpful but it invokes the parser.

Same Content — Two Ways

Using innerHTML:

node.innerHTML = "<div class='bingo'><p>B3</p><p>I2</p><p>N4</p></div>";
            

Using the manipulation APIs:

var div = document.createElement("div"); 
div.setAttribute("class","bingo");
var p = document.createElement("p");
p.appendChild(document.createTextNode("B3"));
div.appendChild(p);
p = document.createElement("p");
p.appendChild(document.createTextNode("I2"));
div.appendChild(p);
p = document.createElement("p");
p.appendChild(document.createTextNode("N4"));
div.appendChild(p);
node.appendChild(div);