O'Reilly logo

HTML5 For Dummies® Quick Reference by Andy Harris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required