"Danny@Kendal" wrote:
I want to change the styling of several <div> elements with just one
onMouseOver event.
"getElementsByClassName" would be ideal if it hadn't been rejected.
I can't seem to make getElementsByTagName work and all the references I've
seen don't help.
The page in question has a variable number of <div> elements because I
generate it with a server-side vbscript.
I could create sequentially numbered IDs and write a short javascript to
loop through the ID numbers (example below) but is there a more elegant
solution?
eg:
<div id="ref1" class="myclass"...
<div id="ref2" class="myclass"...
<div id="ref3" class="myclass"...
<div id="ref4" class="myclass"...
<div id="ref5" class="myclass"...
then
for(i=1;i<=5;i++)
{
idRef = "ref" + i
document.getElementById(idRef).style.blahblahblah = morestuf
}
You don't need the variable assignment, but what you've got is the way to do
it. Since the number of DIVs is controlled by the server, you can have it sent
a length in client-side javascript
:
var numberOfDivs = <%= numberOfDivs %>;
for (var i = 1; i <= numberOfDivs; i++) { // ...
but a better solution would be:
var i = 1, theDiv;
while ((theDiv = document.getElementById('ref' + i++)) != null) {
theDiv.style.color = 'Red';
}
Providing the DIVs are number sequentially starting at 1, your code will
always work, no matter how many DIVs you output. I'm not sure why you couldn't
get a getElementsByTagName() working, it would be (although slower then the
algorithm shown above):
var divs = document.getElementsByTagName('div');
if (divs) {
for (var i = 0; i < divs.length; i++) {
if (divs[i].className == 'myclass') {
divs[i].style.color = 'Red';
}
}
}
Lastly, you might be better off having two classes, one with each set of
styles, in which case you can do:
var i = 1, theDiv;
while ((theDiv = document.getElementById('ref' + i++)) != null) {
theDiv.className = 'myclassWithColorRed';
}
--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ -
http://jibbering.com/faq