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?
Save a table of all elements using; (document.all || document.getElementsByTagName('*')) then loop through checking for className matches and substitute the new class. Using a loop, pass the IDs in turn to document.getElementById and set the className property to whatever;
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) } Code (markup): // 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; } Code (markup):
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...