Javascript - get elements by class

Thursday, August 19, 2010

I will show you two ways to get an element by class: using getElementsByTagName or creating a getElementByClass function:

1. Using getElementsByTagName
This code loops through each element of the page and check`s it`s class name:
for(var i=0;i<document.getElementsByTagName('*').length;i++){
if(document.getElementsByTagName('*')[i].className == 'YOUR-CLASS'){
document.getElementsByTagName('*')[i].style.backgroundColor = 'black';
}
}

2. Creating a getElementsByClass function
This code creates the getElementsByClass function what returns an array of elements with the selected class name:
document.getElementsByClass = function(class){
var itemsfound = new Array;
var elements = document.getElementsByTagName('*');
for(var i=0;i<elements.length;i++){
if(elements[i].className == class){
itemsfound.push(elements[i]);
}
}
return itemsfound;
}
Use it in the following way to select only the element with the specified index:
document.getElementsByClass('YOUR-CLASS')[0].style.backgroundColor = 'black';
Or use this if you want to select each element:
for(var i=0;i<=document.getElementsByClass('YOUR-CLASS').length;i++){
document.getElementsByClass('YOUR-CLASS')[i].style.backgroundColor = 'black';
}
Note: Javascript is case sensitive

5 comments:

This approach is not very cross-platform. You should consider using jquery (or another framework that provides platform transparency):

$("div.myclass").css("background", "red");

I`we tested it in the latest versions of Opera, Firefox and Chrome and it worked.

A little note, in the
"Or use this if you want to select each element:"
section instead of
"for(var i=0;i<=document.getElementsByClass.length;i++){"

"for(var i=0;i<=document.getElementsByClass('myclassname').length;i++){"

would be good.

Hoops.... I will fix it in a moment.

Thanks !

very good tips to read & follow, thanks

Post a Comment