Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

In JavaScript, the getElementBy methods provide easy access to any element or groups of elements in a document without relying on parent/child relationships of nodes. The three most commonly used ways to access elements are

  • getElementById

  • getElementsByTagName

  • getElementsByClassName

getElementById

By far the most widely used method for selecting elements, getElementById is essential to modern web development. With this handy little tool, you can find and work with any element simply by referencing a unique id attribute. No matter what else happens in the HTML document, getElementById will always be there for you and will reliably select the exact element that you want.

This example demonstrates the awesome power of getElementById to enable you to keep all your JavaScript together in your document or to modularize your code. By using getElementById, you can work with any element, anywhere in your document just as long as you know its id.

 Using getElementById
 


 

You drove ___
miles.

You used ___
gallons of gas.

Your MPG is ___.

getElementsByTagName

The getElementsByTagName method returns a node list of all the elements with the specified tag name. For example, getElementsByTagName is used to select all h1 elements and change their innerHTML properties to sequential numbers.

 Using getElementsByTagName
 


 

this text will go away

this will get overwritten

JavaScript will erase this

getElementsByClassName

The getElementsByClassName method works in much the same way as the getElementsByTagName, but it uses the values of the class attribute to select elements. This function selects elements with a class of error and will change the value of their innerHTML property.

 Using getElementsByClassName
 
 

 
 
 

(continued)

The result of running this code in a web browser and entering a wrong answer is shown here.

Using the<span class=
getElementsByClassNa
Using the getElementsByClassName to select an element for displaying an error message.

Notice that the code above uses an onclick attribute inside the button element. This is an example of a DOM event handler attribute.

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: