1. Technology

JavaScript By Example

Document Object Model: 4. Get Nodes For A Class

By

The only difference of any significance between retrieving all the elements with a particular class attribute as compared to retrieving all of the elements with a particular name or tag name is that not all modern browsers support getElementsByClassName. This particular method for retrieving nodes was originally omitted from the Document Object Model and it was only after lots of web sites started implementing their own code to do this retrieval that some browsers decided that they should add their own version.

What this means is that we cannot rely on our visitor's browser having an implementation of this method and so need to use feature sensing to determine whether or not the browser supports it. The preferable way to implement this feature sensing is to test if it isn't supported and to add our own method that will perform that processing in that case while using the browser's built in method if it exists. The following example demonstrates how to do this and makes use of the method to add some text to the end of each element that has a class of 'red'.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D04</title>
</head>
<body>
<p class="red">First paragraph.</p>
<p>Second Paragraph.</p>
<p class="red last">Third Paragtraph.</p>
<script type="text/javascript" src="exampleD04.js"></script>
</body>
</html>

JavaScript


var node;
if (!document.getElementsByClassName)
document.getElementsByClassName = function(cl) {
var retNode, myclass, elem, classes;
retnode = [];
myclass = new RegExp('\\b'+cl+'\\b');
elem = this.getElementsByTagName('*');
for (var i = 0, ii = elem.length; i < ii; i++) {
classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
}
return retnode;
};
node = document.getElementsByClassName('red');
for (var i = node.length-1; i>=0; i--) {
node[i].innerHTML += ' Red.';
}

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Get Nodes For A Class

©2014 About.com. All rights reserved.