Web Hosting - Submit articles - Debt Consolidation - vBulletin Hosting - Find jobs

PDA

View Full Version : get multiple elements by class


Greg-J
Apr 24th 2006, 1:43 pm
The short of it is that I am trying to change the background color of all elements with a particular class name. I know there is no getElementsByClassName (wouldn't it be nice if there were?), but is there a simple way to do it?

Alternatively, is there a way to apply changes to multiple id's?

Logic Ali
Apr 24th 2006, 5:24 pm
The short of it is that I am trying to change the background color of all elements with a particular class name. I know there is no getElementsByClassName (wouldn't it be nice if there were?), but is there a simple way to do it?



Save a table of all elements using;

(document.all || document.getElementsByTagName('*'))

then loop through checking for className matches and substitute
the new class.


Alternatively, is there a way to apply changes to multiple id's?


Using a loop, pass the IDs in turn to document.getElementById and set the className property to whatever;

exam
Apr 25th 2006, 5:11 pm
You're not the first person to wish that was built in- There's implementations of this a hundred times over.
/*
Written by Jonathan Snook, http://www.snook.ca/jonathan
Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}


// http://www.styleassistant.de/tips/tip100.htm

function getElementsByClassName(class_name)
{
var all_obj,ret_obj=new Array(),j=0,teststr;

if(document.all)all_obj=document.all;
else if(document.getElementsByTagName && !document.all)
all_obj=document.getElementsByTagName("*");

for(i=0;i<all_obj.length;i++)
{
if(all_obj[i].className.indexOf(class_name)!=-1)
{
teststr=","+all_obj[i].className.split(" ").join(",")+",";
if(teststr.indexOf(","+class_name+",")!=-1)
{
ret_obj[j]=all_obj[i];
j++;
}
}
}
return ret_obj;
}

Greg-J
Apr 25th 2006, 6:36 pm
Thank you both. I did end up going with a getElementsByClass() function and it works beautifully.

On another note; How could they overlook something like that? Surely it would be more efficient as a standard function...