Join the Discussion
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');
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');
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.