Retrieving Elements By CSS Class



Recently, I needed to retrieve all of the DIVs in an area that used a specific CSS class. Although browsers allow you to retrieve HTML elements in a variety of ways, such as by identifier or by tag type, there is no way to retrieve elements by class.



So, the best bet is to roll our own. An easy way to do this is to use the Element.getElementsByTagName() function call. Just like it sounds, it retrieves an array of all subchildren of Element that have a specific tag name.

So you could do something like this:


var MyElement = document.getElementById("MyDiv");
ChildDIVs = MyElement.getElementsByTagName('div');


Notice that we use a lower case 'div' in the getElementsByTagName() call-this isn't just happenstance. Some versions of Safari require the getElementsByTagName parameter to be in lower case when you are using pages that have XHTML strict doctypes - so to play it safe we'll use lower case.

Now what? With this array we should be able to loop through and retrieve the name of each class and compare it to our target class name. We can then filter the array for the elements that we do want.

The completed code for our getElementsByClass function is below.


function getElementsByClass(ElementRoot, ElementType, ClassName)
{
var ElementArray = new Array();
var UnfilteredElements = new Array();

UnfilteredElements = ElementRoot.getElementsByTagName(ElementType);
for (var i = 0; i < UnfilteredElements.length; i++)
{
if (UnfilteredElements[i].className == ClassName)
ElementArray[ElementArray.length] = UnfilteredElements[i];
}
return (ElementArray);
}


Although this is functional, there is a way we can improve upon it which I'll cover next time.

No comments :