Getting Element References in JavaScript

This page describes and demonstrates various methods for obtaining references to elements in your documents. We start with the familiar and basic getElementById and the well-supported getElementsByTagName. We then proceed to the newer getElementsByClassName, querySelector, and querySelectorAll methods supported by up-to-date browsers.

We provide information on case-sensitivity and on the node lists returned by most of these methods and how node lists are different from regular arrays.

The document.getElementById Method

The simplest and most familiar way to obtain a reference to an element is the getElementById method. While the other methods described on this page are supported by HTML elements as well as the document, the getElementById method is available only on document.

Pass an unique ID to this method and it returns a single element with a matching ID or null if no match is found. Then you can use this reference to apply properties to the element or read properties from it. You may want to check for the existence of the element in your code before working with it, as demonstrated in the following:

// get reference to element with id 'demo'
var el = document.getElementById('demo');

// check to be sure el exists
if (el) {
    // set a property = 'hidden';
    // read a property

Both HTML4 and HTML5 specify rules for valid ID attributes.[1] However, for best results, you may want to establish stricter guidelines for use with JavaScript and CSS. An ID should begin with a letter and consist only of letters (upper or lower case), digits, hyphens, or underscores. Inclusion of other characters may cause problems.

The getElementsByTagName Method

Pass a tag name to the getElementsByTagName method and it will return a list of matching elements either within the document or within the element on which it is invoked. In other words, you can get a list of elements of a particular type in the whole document or just within a particular element.

The list of elements returned from this method is called a node list. It has some features of an array; you can obtain its length, and you can use array indexing to access the elements of the list.

For example, the following code snippet will obtain a node list containing references to all the unordered lists in the document. Then we invoke the getElementsByTagName method on the first unordered list in the document (uLists[0]) to get a node list containing all its list items. Then we determine how many list items are in this first unordered list.

// get list of ul elements in document
var uLists = document.getElementsByTagName('ul');

// get list items in first ul
var items = uLists[0].getElementsByTagName('li');

alert(items.length); // how many list items in first ul

You can expect the getElementsByTagName method to be supported by virtually any JavaScript-enabled browser in use today. You can pass '*' to the method to obtain a list of all elements in the document, except in Internet Explorer 5.5 and earlier.

The getElementsByClassName Method

The getElementsByClassName method can be invoked on either the document or an element. It returns a live node list. It is supported by Firefox, Chrome, Safari, Opera, and Internet Explorer as of version 9.

An example demonstrates with a show-hide JavaScript. First we use object detection to be sure errors are not triggered in browsers that do not support the method. Then we obtain a list of elements with the desired class. Then we loop through this list and assign a click handler to each element.

// .getElementsByClassName method supported?
if ( document.getElementsByClassName ) {
    // get list of links with 'show-hide' class
    var links = document.getElementsByClassName('show-hide');
    // loop through links
    for (var i=0, len=links.length; i<len; i++) {
        // add click handler to each link in list
        links[i].onclick = toggleVisibility;

The querySelector and querySelectorAll Methods

The querySelector and querySelectorAll methods can be invoked on the document, on elements, or on document fragments. These methods are supported in Internet Explorer 8 and above as well as Firefox, Chrome, Safari, and Opera.

The querySelector method returns the first matching element in document order or null. The querySelectorAll method returns a static node list; that is, the node list does not respond to changes in the document.

An example demonstrates querySelectorAll with a toggle-display JavaScript. First we use object detection to be sure errors are not triggered in browsers that do not support the method. Then we obtain a list of elements with the desired selector. Then we loop through this list and assign a click handler to each element.

// Check if querySelectorAll method supported
if ( document.querySelectorAll ) {
    // get list of elements matching selector
    var list = document.querySelectorAll('dl.toggle dt');
    // loop through list of matching elements
    for (var i=0, len = list.length; i<len; i++) {
        // attach click handler to each
        list[i].onclick = toggleDDVisibility;

Case Sensitivity for Tag Names, IDs and Classes

Both HTML and CSS are case insensitive. However, there are times when case sensitivity applies. IDs and class names are case sensitive. For more information on this see Case Sensitivity in the SitePoint Reference.

Tag names are not case sensitive for HTML, but XML is case sensitive and XHTML expects tags to be lower case.

For best results, be case consistent with your tag names, IDs, and class names when working with HTML, CSS, and JavaScript. Generally, lower case is recommended with inclusion of intercap when appropriate.

About Node Lists

The getElementsByTagName and getElementsByClassName methods return live node lists. Live node lists are updated with any changes in the document. The querySelectorAll method returns a static node list. It is not updated if there are changes in the document. Instead it takes a snapshot of the document at the time it is invoked.

Node lists are returned in document order. They are like arrays in some ways, but are not true arrays. You can not apply array methods directly to node lists. But as demonstrated above, you can access the length property and use array indexing to access individual items in the list.

Find out more about the array-like nature of node lists and HTML collections.

  1. See the specifications on IDs for HTML4 and HTML5 and a stackoverflow discussion on valid IDs. ^