01 November, 2010

Get elements by class name in javascript

At times, i need function to get all the elements using class name in javascript. But since such function does not exist as in javascript, so i thought of creating a similar function that can be used to get elements by class name.
Here is the code snippet:

function getElementByClassName(strClassName) {
var eleNames = new Array();
var totalFrms = document.forms.length;
for(var i = 0; i < totalFrms; i++) {
//alert(document.forms[i].elements.length);
var eleLen = document.forms[i].elements.length;
for(var j = 0; j < eleLen; j++) {
if(strClassName === document.forms[i].elements[j].className) {
eleNames.push(document.forms[i].elements[j]);
}
}
}
return eleNames;
/*
for(t = 0; t < eleNames.length; t++) {
alert(eleNames[t].type);
}
*/
}
getElementByClassName("user_text");
Thats is. Hope this helps someone.

No comments: