PDA

View Full Version : Access Any Element in your DOM using a Class Name


omega113
06-11-2008, 11:27 PM
I use this function a lot. getElementsById doesnt work all the time in IE

Use the below given function to access object of any tag in your DOM.

To access 2nd Img tag whose class name is "mountain"
call getArrayByClassName("mountain","img")[1];

function getArrayByClassName(clsName,tag){
var retVal = new Array();
if (tag == null) { tag="*"; }
var elements = document.getElementsByTagName(tag);
for(var i = 0;i < elements.length;i++){
var classes = elements[i].className.split(" ");
for(var j = 0;j < classes.length;j++){
if(classes[j] == clsName)
retVal.push(elements[i]);
}}return retVal;
}

fside
06-12-2008, 02:30 AM
Hi. A getElementsByClassName is one of the first script 'extensions' (or workarounds) to go in any javascript library. Look up Dustin Diaz, and getElementsByClassName (http://www.dustindiaz.com/getelementsbyclass/).

I believe his was the fastest tested against the latest system-level method for javascript in FireFox, in the expected FF3. But it was still 18x slower that the new FF3 method. The thing about it is that, just as you have, most programmers have their routine return an ARRAY of elements. But it may be that this new Firefox getElementsByClassName may return an object instead?