Retrieving Page Elements via the DOM

How can you use the Document Object Model to access the various parts of your Web page? This tutorial shows you how to retrieve HTML elements using three handy DOM methods.

In the last DOM article, you learned that the DOM represents the contents of a Web page as a "tree" of JavaScript objects. By accessing the parts of the tree, called the nodes, you can read existing page content, alter content, and even add new content from scratch.

In this article you'll learn how to locate and retrieve the elements of a Web page using JavaScript and the DOM.

Here's a simple XHTML Web page:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>My Web Page</title>
  </head>
  <body>
    <h1 class="intro">The Widget Company</h1>
    <p>Welcome to the Widget Company!</p>
    <p>Widgets for sale:</p>
    <ul>
      <li id="widget1"><a href="superwidget.html">SuperWidget</a></li>
      <li id="widget2"><a href="megawidget.html">MegaWidget</a></li>
      <li id="widget3"><a href="wonderwidget.html">WonderWidget</a></li>
    </ul>
    <form method="post" action="">
      <div>
        <label for="widgetName">Enter the name of a widget to buy it:</label>
        <input type="text" name="widgetName" id="widgetName" />
        <input type="submit" name="buy" value="Buy" />
      </div>
    </form>
  </body>
</html>

All the elements in this page can be accessed via the single Document object that represents the page.

Finding elements by ID

The easiest way to access an element is via its id attribute, because an element's id is unique in the page. Here's how it's done:


var element = document.getElementById( elementId );

So you could access the second list item in the above Web page ("MegaWidget") as follows:


var widget2 = document.getElementById( "widget2" );
alert( widget2 );

The above code displays an alert box containing:


[object HTMLLIElement]

So, document.getElementById() returns an object representing the element (in this case an HTMLLIElement, or "HTML list item element", object).

While most modern browsers display the object type (such as [object HTMLLIElement]), Internet Explorer (at the time of writing) rather unhelpfully just displays [object].

Finding elements by tag name

Using document.getElementById() is all very well if the element you're after has an ID (or you can easily add one). How do you access elements that don't have an ID?

One way is to find all the elements of certain type, such as all h1 elements or all p elements. You can do this using document.getElementsByTagName():


var elements = document.getElementsByTagName( tagName );

document.getElementsByTagName() returns a collection of all the elements with that particular tag name. For example, this code retrieves the two paragraph elements in the Web page:


var paragraphs = document.getElementsByTagName( "p" );
alert( paragraphs );

The above code displays:


[object HTMLCollection]

A collection is simply a special type of object that itself contains a list of objects — in this case, HTMLParagraphElement objects. You can loop through the collection with a for loop, using the collection's length property to determine how many objects are in the collection:


var paragraphs = document.getElementsByTagName( "p" );
for ( var i = 0; i < paragraphs.length; i++ ) { 
  alert( paragraphs[i] );
}

This code displays two alert boxes, each containing:


[object HTMLParagraphElement]

Finding elements via their name attributes

If you have elements within your page that have name attributes — such as form input fields and select menus — then you can retrieve those elements via their names with document.getElementsByName:


var elements = document.getElementsByName( name );

As with getElementsByTagName(), getElementsByName() returns a collection of elements with the given name.

For example:


var widgetNameField = document.getElementsByName( "widgetName" )[0];
alert( widgetNameField );

This code pops up an alert displaying the object that represents the "widgetName" input text field in the form:


[object HTMLInputElement]

Finding elements by their relationship

Because each node in the DOM tree is related to every other node, once you have retrieved one node you can theoretically access any other node in the tree by hopping between the nodes. To do this, you use properties of each node such as parentNode (to retrieve the node's parent) and childNodes (to retrieve the children of the node). You'll learn more about this technique in the next tutorial.

Digging deep into elements

In this tutorial you learned how to retrieve any HTML element within a Web page. You used getElementById() to retrieve an element with a specific ID, getElementsByTagName() to get all the elements of a certain type, and getElementsByName() to find all elements with a particular name attribute.

However, simply getting these element objects doesn't really help much. How do you access the contents of an element? Find out in our next tutorial, Looking inside DOM page elements.

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page