Finding Your Way Around

The DOM offers many ways to move around and find what you want. As any HTML or XML document is essentially a collection of elements arranged in a particular hierarchy, we traverse the DOM using the elements as markers . In fact, a lot of what we do in the DOM is akin to wayfinding: using elements (especially uniquely id-ed ones) as signposts, which let us know where we are in our documents and help us get deeper and deeper into our documents without losing our way.

Let’s take the following snippet of (X)HTML, for example:

<div id="content">
  <h1>This is a heading</h1>
  <p>This is a paragraph.</p>
  <h2>This is another heading</h2>
  <p>This is another paragraph.</p>
  <p>Yet another paragraph.</p>

If you wanted to find the h2 in this snippet, you would need to use two of JavaScript’s interfaces to the DOM, getElementById( ) and getElementsByTagName( ):

var the_div = document.getElementById( 'content' );
var h2s     = the_div.getElementsByTagName( 'h2' )
var the_h2  = h2s[0];

In the first line, you use the DOM to find an element on the page with an id equal to content and assign it to the variable the_div.


If you don’t already have an element reference to begin with, default to the document object, which refers to the page. getElementById( ) is always used with document.

Once you have your container div assigned to the_div, you can proceed to find the h2 you want, using getElementsByTagName( ) (line 2). That method returns an array of elements (h2s), referred to as ...

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.