• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / The Document Object Model / Retrieving Page Elements via the DOM

Retrieving Page Elements via the DOM

31 October 2008 / Leave a Comment

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 my next tutorial, Looking inside DOM page elements.

Filed Under: The Document Object Model Tagged With: collections, elements, getElementById(), getElementsByName(), getElementsByTagName(), input, length property, lists, looping, nodes, objects, paragraph, text field

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits