PDA

View Full Version : adding numeric suffix to element id



tiki
04-07-2006, 12:59 PM
Sorry for the dumb question, I'm a Javascript newb.
Basically, I need to add a numeric suffix to the ID so I can apply colors to multiple DOM documents.
The problem is I don't know how to define the numid variable.

Any help would be greatly appreciated.


function update(elemchange)
{

var numid =
switch(elemchange)
{

case "linkcolor": {
var obj = document.getElementById('link' + numid);
obj.style.color="900000";
break;
}
case "textcolor": {
var obj = document.getElementById('text' + numid);
obj.style.color="ff0000";
break;
}
}

}


<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="center">
<span id="link1" class="link">link</span>
<span id="link2" class="link">link</span>
<span id="link3" class="link">link</span>
<span id="link4" class="link">link</span>
<span id="link5" class="link">link</span></td>
<td align="center">
<span id="text1" class="text">text</span>
<span id="text2" class="text">text</span>
<span id="text3" class="text">text</span>
<span id="text4" class="text">text</span>
<span id="text5" class="text">text</span></td>
</tr>
<tr>
<td align="center"><a href="#" id="linkcolor" onclick="update('linkcolor')">click</a></td>
<td align="center"><a href="#" id="textcolor" onclick="update('textcolor')">click</a></td> </tr>
</table>

Twey
04-07-2006, 01:17 PM
I'm not sure I quite get what you're trying to do here, but here's my stab at it:
function update(elemchange)
{
if(elemchange == "linkcolor") // Switch is overkill for only two possibilities
for(var i = 1; var curel = document.getElementById("text" + i); i++) // Loop through all the IDs until we come to a non-existent element
curel.style.color="#900000"; // Numerical colour values must start with a hash (#)!
else // We can anticipate that it should either be one or the other, so we can leave it open-ended
for(var i = 1; var curel = document.getElementById("text" + i); i++)
curel.style.color="#ff0000";
}

tiki
04-07-2006, 01:23 PM
Hi Twey,
Thank you so much so your help, it works perfectly :)

Best regards,
Tiki

mwinter
04-07-2006, 02:01 PM
for(var i = 1; var curel = document.getElementById("text" + i); i++)A var statement isn't permitted in the second clause of a for statement, only the first. :)

Mike

Twey
04-07-2006, 04:47 PM
Actually, this can be simplified further:
function update(elemchange)
{
var curel,
colour = "#" + (elemchange == "linkcolor" ? "90" : "ff") + "0000";
for(var i = 1;curel = document.getElementById("text" + i); i++)
curel.style.color=colour;
}

/EDIT: Whoops, sorry, Mike. Only saw your comment, despite it being above mine, about four hours later. >.<