Behold: The New JavaScript Selection Options

JavaScript is usually used to interact with the Web page. Generally, the programmer uses the document.getElementById() method to create a variable based on a page element. This mechanism requires the element to have an id attribute. HTML5 incorporates some new ways to select elements from the page.

document.getElementsByClassName()

Sometimes you’ll want to apply code to all elements in a particular class. The getElementsByClassName() function returns an array of all the elements in a particular class. For example, look at the following code:

  function init(){

    specP = document.getElementsByClassName(“special”);

    alert(specP.length);

    for(i = 0; i < specP.length; i++){

      alert(specP[i].innerHTML);

    } // end for

  } // end function

This routine creates an array of all of the elements on the current page with the class special. It then steps through each element of that array and alerts the content of that element.

Note that getElementsByClassName() does not return a single element like getElementById(). Instead, it returns an array. Generally, you’ll use a for loop to step through the array and do something to each element.

The class does not need to have any CSS associated with it. This can be an easy way to mark a set of elements you’ll want to do something with.

document.getElementsByTagName()

The getElementsByTagName() method allows you to quickly retrieve all the elements with a given tag name. For example, you could ...

Get HTML5 For Dummies® Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.