PDA

View Full Version : How do I change the class of multiple divs?



franky20
06-26-2007, 04:30 PM
How do I change the class of multiple divs at the same time using the "document.getElementsByTagName" function?
It seems like I can do everything but change the class of the objects defined with the "document.getElementsByTagName" function; I can display an alert stating how many objects are in that function, how many have a certain class...
but I cant seem to change the class!
I am using the following javascript to try and change the class:



function divc2(){
divi=document.getElementsByTagName('div');
divi.className='class1';
}
function divc1(){
divi=document.getElementsByTagName('div');
divi.className='class2';
}

my stylesheet:


.class1{
color:#000fff;
}
.class2{
color:#5e5e5e;
}

and the body of my test page is:


<div class="class1" id="div">Div1</div><div class="class1" id="div2">Div2</div>
<a href="javascript:divc2()">Change To Class2</a> | <a href="javascript:divc1()">Change To Class1</a>

Is there something wrong with this code? It seems to me like it should do the job, but it doesn't. I'm using the FireBug extension for FireFox and that doesn't come up with any errors, so why doesn't it work?

(My Test Page Is Located At http://dev.formulationx.com/dlinkt/)

Twey
06-26-2007, 06:12 PM
The object returned by getElementsByTagName() is a collection, not a single element. You can set arbitrary properties on any object in ECMAScript (hence the lack of an error), but setting the className on the collection doesn't do much: you need to iterate through its members and set each className individually.
function divc1(){
var divs = document.getElementsByTagName('div');
if(divs)
for(var i = 0, e = divs[0], n = divs.length; i < n; e = divs[++i])
e.className='class2';
}

franky20
06-27-2007, 02:44 AM
Thanks, That script worked perfect!:)
(I'm not that grate at javascript)