Forum Moderators: open

Message Too Old, No Replies

How to use a passed argument as a property or method

         

doctormelodious

5:45 am on Jul 4, 2004 (gmt 0)

10+ Year Member




<script language="JavaScript">
<!-- Begin
function testThing(theLink) {
if (document.all) {
alert(document.all.theLink.style.color);
}
else{
alert(document.links.theLink.style.color);
}
}
//-->
</script>

Greetings,

Actually, the title of the message is wrong. I'm trying to pass a string, containing the ID of an element (not a property or method), to a script. But the script fails. I've tried calling it as testThing(IDofLink); and testThing('IDofLink');, but either way I get no alert. However, if I hardwire the ID of the link into the script (in place of "theLink"), then I get the alert.

What am I doing wrong?

Thanks!
Perry

doctormelodious

6:16 am on Jul 4, 2004 (gmt 0)

10+ Year Member



Before I posted this message, I searched and searched for the answer. Of course, as soon as I had posted it, I found the answer!


fred = eval("document.all." + theLink + ".style.color");
alert(fred)

Bernard Marx

9:24 am on Jul 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



No, no, no! It works of course, but all that wrangling with quotes is inefficient, and unnecessary.

fred = document.all[theLink].style.color;

Will be fine.
NEVER use eval. Any 'dot' property can be accessed via a string using [] notation.

But, document all is only supported in IE. Use this instead:

fred = document.getElementById(theLink).style.color

doctormelodious

9:58 am on Jul 4, 2004 (gmt 0)

10+ Year Member



Thanks Bernard!