When developing websites, it’s good practice to separate behaviour (JavaScript) from structure and presentation using The Document Object Model (DOM). This indepth tutorial is all you’ll need in order to get a good understanding on how to do it.

Clean Up Your Page, Removing Bad Behaviour

By Luke Dingle | May 7th, 2008 |
Print This Article

Accessing Multiple Elements

So we’ve seen how easy it is to hunt down a single element and apply some code to it but of course we don’t want to have to give every element a unique id and code them all by hand. We want to be able to ‘batch process’ a whole lot of elements.

Perhaps we want to access all of the images in the document and add a function that alerts the alt=”" text each time a user clicks the image (not a very useful real life example).

To access either all elements or all elements of a single type, we can use getElementsByTagName. This function takes a string as an argument and with the string looks for all of the HTML tags that match. The function will return a list of all matching nodes within the document. If you wanted to access all of the nodes in the document, regardless of the tag type you can send the string ‘*’. getElementsByTagName will return an array of everything.

The below will tackle the example above and add an alert to all of the images along with a copyright notice. Add the following code to the initiatePage function you set up before – add just below the } closing brace.

// Get references to all of the images in the document using getElementsByTagName
	// The results are returned in an array
	var imgs = document.getElementsByTagName('img');

	// count how many images there are and loop through adding a simple onclick function
	// to alert the alt text to the user...

	nm = imgs.length;

	for (i=0; i<nm; i++)
	{
		// date.getFullYear() is using the date object declared earlier
		imgs[i].onclick = function () { alert(this.getAttribute('alt') + '\n\n \t\t(c) ' + date.getFullYear());};
	}

See results at : www.lukedingle.com/scripts/dom.php?getCode

Again, this was a simple thing to perform. The last code used the inline function declaration explained earlier and depending on how many images this was to be applied to, potentially saved 10’s of onclick=”" inline event handlers from clogging up the page.

So the above example will track down every single image on the page but what if you wanted to focus on a specific group of elements in the document rather than all of them?

There are a few ways to go about this:

The first way is to use the getElementsByTagName on a node that you have stored in a variable. This will return all of that type of element that are child elements of the node stored in the variable. Confused? Never mind, I’ll explain this further.

In our working HTML document, I want to access all of the links that are in the #header of the document. I don’t want to change any of the other links, just those. The following code – which will be added to the initiatePage function will use the header variable we stored earlier when adding the background effects and retrieve all of the links inside of it. To these links, we will add a function that takes the title text of the link and displays it underneath the menu when the user holds their mouse over it.

Add the following code into the initiatePage function just after

header.onmouseover = changeBackground;
header.onmouseout = changeBackground;

//let's get all of the links found inside the header div
	// we will add the showInfo function to the mouseover eventHandler
	// to hide the details 

	var headerLinks = header.getElementsByTagName('a');

	// count how many there are and add the function to them
	nm = headerLinks.length

	for (i=0; i<nm; i++)
	{
		headerLinks[i].onmouseover = showInfo;
		headerLinks[i].onmouseout  = hideInfo;
	}

Okay, the above code is pretty simple again. What we are doing is getting an array of all the links inside the #header div. Then we loop through adding the two functions to onmouseover and onmouse out.

Now for the showInfo and hideInfo functions. Don’t get too frightened by as the details will be explained afterwards:

// Store a reference to the div that we will add the content to
	// the id is given in the global variable at the top of this script
	var workingDiv = document.getElementById(infoDiv);

	// We want to clear all the content from the div before we add the new
	// content...
	var emptyDiv = workingDiv.cloneNode(false);

	// This new empty div now goes before the old one

	workingDiv.parentNode.insertBefore(emptyDiv, workingDiv);

	// Now get rid of the old one all together

	workingDiv.parentNode.removeChild(workingDiv);

	// Insert the new text into the new div

	emptyDiv.appendChild(document.createTextNode(this.getAttribute('title')));

}
function hideInfo ()
{
	// Store a reference to the div that we will add the content to
	// the id is given in the global variable at the top of this script
	var workingDiv = document.getElementById(infoDiv);

	// We want to clear all the content from the div before we add the new
	// content...
	var emptyDiv = workingDiv.cloneNode(false);

	// This new empty div now goes before the old one

	workingDiv.parentNode.insertBefore(emptyDiv, workingDiv);

	// Now get rid of the old one all together

	workingDiv.parentNode.removeChild(workingDiv);
}

See results at : www.lukedingle.com/scripts/dom.php?getCode

These two functions are very simple again but they are introducing a few new functions the DOM gives us to manipulate our documents.

Pages: 1 2 3

About The Author

Article By: Luke Dingle
Luke Dingle

Luke Dingle is a professional web developer working in Tasmania, Australia. Although much of his time revolves around writing, then re-writing PHP and JavaScript code for others, he manages to find time to work on pet projects like http://www.openthource.com and http://www.lukedingle.com. Luke likes to juggle and play piano but usually runs out of time as his attempts to lobby the government for 3 extra hours in each day have so far failed.

You can view other posts by Luke Dingle. Or you can visit Luke's website at: http://www.lukedingle.com

Comments

  1. Alex said :

    I found your site on technorati and read a few of your other posts. Keep up the good work. I just added your RSS feed to my Google News Reader. Looking forward to reading more from you down the road!

  2. Alex said :

    Your blog is interesting!

    Keep up the good work!

  3. Luke Dingle said :

    Hey Alex,

    Glad you like what we’re doing here. Hopefully we’ll keep feeding you the good stuff through RSS.

Trackbacks

  1. y coded
  2. jQuery - Why Wouldn’t You?

Do you have something to say?