Referencing HTML Elements via JavaScript

by kirupa  |  13 March 2011

  Have questions? Discuss this HTML 5 tutorial with others on the forums.

You can do a lot of cool and awesome things using just HTML (and CSS, SVG, etc.). With that said, you can do a lot of cooler and awesomer things when you mix HTML with a dash of JavaScript! In order to do that, you need to be able to reference your HTML elements via JavaScript. In this article, you will learn to do just that using two functions built for exactly this purpose - getElementById and getElementsByTagName.

Setting up our Example
All good stories need a setting - a place where the main character fights some bad guys and blows up various unrelated structures. In our case, that will be the following example:

<!DOCTYPE html>
<html lang="en-us">
 
<head>
<meta charset="utf-8">
<title>Referencing Elements Example</title>
</head>
 
<body>
<p>Up and atom!</p>
<p>Ay carumba!</p>
 
<script>
// do something here
</script>
 
</body>
</html>

This is a very simple HTML 5 document that contains two p tags that display two Simpsons quotes in the most boring of ways possible - the browser's default font style:

[ our example's output ]

To help you learn more about getElementById and getElementsByTagName, we will be modifying the source from this simple document to see how they work.

GetElementById
The most common way for you to reference an element is by accessing an HTML element by its id. The id is a unique name you give an element in your HTML. Note the emphasis on unique. Your document can only have one unique id value in it.

Looking at our example, lets try to mess with our p tags:

<p>Up and atom!</p>
<p>Ay carumba!</p>

If you wanted to access the first p tag directly using code, you'll need to name it by giving it an id. The way you name something in HTML is by adding the id attribute and the value to whatever HTML element you wish to name. For our example, let's name our first p tag "quoteOne". Your markup will look as follows:

<p id="quoteOne">Hello, World!</p>

Notice that the opening p tag is followed by id="quoteOne" before being closed. Once you have your element named (or ID'ed if it is under 21 - zing!), all that is left is to access it via code.

The JavaScript function that allows you to do this is getElementById, and it looks as follows when used:

<script>
   var quoteElement = document.getElementById("quoteOne");
</script>

The getElementByID function is always called on your document, and it takes one argument - the id of the element you are trying to reference. In our case, the id is quoteOne.

What gets returned is, as you can guess by the function name, the element that matches the id you specified. You can declare a variable to store a pointer to the returned element:

var quoteElement = document.getElementById("quoteOne");;

You will never have more than one element returned with a getElementById call because you cannot name more than one element with the same id.

GetElementsByTagName
You just saw you how you can reference an element by its id. If you are trying to cast a wider net, the other approach is by calling all elements of a particular tag type such as div, table, etc.

Taking our earlier example, let's say we want to get all of the p tags in our document:

<p id="quoteOne">Up and atom!</p>
<p>Ay carumba!</p>

The way you would do this is similar to the getElementById case:

var allElements = document.getElementsByTagName("p");

The major difference is that you use the getElementsByTagName function and pass in the name of the tag whose elements you wish to get a reference to. In our case, that tag is p.

What gets returned is not a single element like you saw before, but instead, you get an array of elements whose tag names are what you specified. An array is something that I will describe in another tutorial, but if you are not familiar with what they are, just think of them as a container that stores many items.

Simple Example - Changing the Background Color of All p Tags
Here is an example of me iterating through the p tags returned by getElementsByTagName and setting the background of this element to be a light blue color:

<script>
var allElements = document.getElementsByTagName("p");
for (var i=0; i < allElements.length; i++)
{
var currentElement = allElements[i];
currentElement.style.backgroundColor = "#D9F5FF";
}
</script>

Here is a screenshot of what you see in your browser when the above script is run:

[ changing colors easily! ]

See, this was pretty straightforward! If you didn't have getElementsByTagName, you would have to manually traverse your DOM and do all of this yourself.

Scoping your Search
In my example, I am running the getElementsByTagName function starting with the document itself:

var allElements = document.getElementsByTagName("p");

You can actually choose to constrain your search to only the subtree (or descendants) of the element you are actually interested in. Simply change "document" to the variable referencing another element, and your search will start with that element as the root instead.

Conclusion
Yes, it is unfair that there exists this separation between your markup and your code. One would have thought society had moved on. Fortunately, you have trailblazing icons in the form of getElementById and getElementsByTagName who transcend these boundaries and make it easy for you to reference an individual named element or a series of elements who share a tag name. May their light keep on shining.

Need Help?

If you have questions, need some assistance on this topic, or just want to chat - please drop by our friendly forums and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out. Plus, we have a large collection of smileys you can use

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly at kirupa[at]kirupa.com.

Cheers!

Kirupa Chinnathambi
about | facebook | twitter

SUPPORTERS:

cloud storage
EdgeCast CDN
kirupa.com's fast and reliable hosting provided by Media Temple. Creative web apps. Make your own free flash banners and photo slideshows.
HTML5 CSS3 Mobile Gallery for iPhone, iPad Flash effects. Art without coding.
Flipping Book - page flip flash component. Flash-Gallery.com - Get your flash photo gallery (flash component or swf gallery
Learn how to advertise on kirupa.com
 
SHARE:



MINI SUPPORTERS: