1. Tech

Your suggestion is on its way!

An email with a link to:

http://javascript.about.com/library/bldom07.htm

was emailed to:

Thanks for sharing About.com with others!

The Javascript DOM

7. getElementsByTagName

clr gif

The biggest difference between the collections that we looked at in the second tutorial and getting by id as we have looked at in the more recent tutorials is that to be able to get by id we need to put an id into the HTML. This is all very well if you just have one or two fields that you want to process but what happens if you want to get all of the divs on a the page to do something with them. Surely there is a better way than having to give each a unique id and access each one separately.

Actually there is a better way because the standard DOM allows you to create your own collection of type of tag that appears on your web page. To do this we just replace document.getElementById with document.getElementsByTagName. Instead of obtaining a single object from our page that has the id that we specified we now get back an array of all of the objects that are identified by a particular tag.

var spanArray = document.getElementsByTagName('span');
alert(spanArray[0].innerHTML);

If we run the above code after the page finishes loading then we will get an alert popup that displays the contents of the first span container on our web page. Subsequent spans can be referenced simply by incrementing the array counter and loop processing to perform the same action for each such tag on our page is easily implemented. Any processing where we know which element of the array we want can also be easily actioned without needing to update the HTML to add an id. Since this could be added to an external Javascript that is already linked into thousands of web pages we can therefore save ourselves the trouble of having to add an id to the tag on each of those pages and simply access it from this array instead.

One container that appears on each and every web page in existance is of particular interest here. Every web page contains a body that contains everything that will appear on the page. We can easily access and update the entire web page (or more specifically global styles applied to the page) by using the following code which doesn't require us to add an id to the body tag.

var theBody = document.getElementsByTagName('body')[0];

Note that in this instance since we know that a page can only ever have one body we only ever need to reference the first such tag.

©2014 About.com. All rights reserved.