Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

function only working on the first div tag

Status
Not open for further replies.

kzn

MIS
Jan 28, 2005
209
GB
Hi

I am having problems with the following code, for some reason the function is only affecting the first <div id="txt"> tag and not the other two. I know by changing each div tag id and running the function 3 times it works. Any help would be appreciated.

Thank you


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<html xmlns="<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
div.red {
color:red;
}
div.blue{
color:blue;
}
</style>
<script type="text/javascript">
function switchColor(elem,one,two) {


theClass = document.getElementById(elem).className;
if(theClass == one) {
document.getElementById(elem).className = two;
} else {
document.getElementById(elem).className = one;
}
}
doit = setInterval("switchColor('txt','red','blue')",500);

</script>
</head>

<body>
<div id="txt">Test 1</div>
<div id="txt">Test 2</div>
<div id="txt">Test 3</div>

</body>
</html>
 
Thanks for the response ... I am a little confused if I did the following. I would get the same response on all of them. So what you are saying is Javascript will only work on one id and it must be unigue, unlike css. Forgive if I am being silly.

Thanks

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<html xmlns="<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#red {
color:red;
}
</style>
</head>

<body>
<div id="red">Test 1</div>
<div id="red">Test 2</div>
<div id="red">Test 3</div>

</body>
</html>
 
IDs should be unique - which means that any particular ID should occur only once in a document. Yours has the same ID 3 times.

You should either use different IDs (e.g. txt1, txt2, txt3, etc), or find another way of referencing the elements (e.g. by tag name, by name, by class, etc), and remove the duplicate IDs.

CSS has nothing to do with this... you don't define IDs in CSS, simply rules that match IDs.

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top