Modifying Page Elements On-the-fly

In the “old days” web developers did everything – and I mean everything – in the local page, right in the code. That meant presentational tags all the way down to JavaScript functions spread throughout the page. We soon found out that was the wrong way to do things. Maintenance is a nightmare and consistency throughout becomes non-existent. Even worse, errors easily worked their way into such a development strategy.

In recent times, we’ve seen the introduction of XHTML and CSS to control the presentation of web pages. It now seems that almost everyone recognizes the benefits of separating presentation code from the content itself. Now developers are realizing that the same benefits can be had with the “behaviour” layer – the JavaScript layer.

In other words, we can do more than just link our JavaScript files instead of putting them locally in the page. What we can do is begin to remove all the function calls and bits and pieces of JavaScript from our pages and instead move the control to the functions themselves. This separates our code layers even further and makes our JavaScript easier to maintain and more powerful.

$2.79
- OR -

Overview

getElementsByTagName

If we are going to remove JavaScript from our code in our local pages, then we need a powerful way to get at things in large chunks. Fortunately, the DOM Core Level 1 provides just such a tool called getElementsByTagName. The W3C explains it like so:

Returns a NodeList of all the Elements with a given tag name in the order in which they would be encountered in a preorder traversal of the Document tree.

Parameters

            tagname - The name of the tag to match on. The special value "*" matches all tags

Return Value

            A new NodeList object containing all the matched Elements.

That sounds a bit technical in typical W3C style. The first thing talked about is a NodeList. A NodeList is an ordered collection of nodes – which is similar to an array. Remember that an array looks like this:

vehicleArray

[0] Car
1] Truck
[2] Van
[3] Sled

And you could use various methods to manipulate the data in such an array. An ordered collection is almost the same thing. It’s simply a collection of the nodes that match the element you specified as the parameter. And there are various ways you can then get at that information. This is exactly what we need.

Reviews

Be the first to write a review

You must me logged in to write a review.