PDA

View Full Version : even simpler innerHTML confusion



neil1967
01-23-2011, 01:42 AM
Can anyone tell me why the string comparison test doesn't work in this javascript function? It works if you use just text between the currentItem div tags, but not when you use html for an image. I even tried to use iso characters instead of angle brackets, as in "<img src=expand.png></img>" and still no dice. Why not?


<html>
<head></head>
<body>
<script language="JavaScript">
function toggleValue()
{
if(document.getElementById("currentItem").innerHTML != "<img src=expand.png></img>")
{
document.getElementById("currentItem").innerHTML = "<img src=expand.png></img>";
}else
{
document.getElementById("currentItem").innerHTML = "<img src=collapse.png></img>";
}
}

//-->
</script>

<table width =" 200" border="0">
<tr>
<td colspan=2><br><center>
<a href="javascript:toggleValue()">Toggle Value</a>
</center></td>

</tr>
<tr>
<td>
<strong>Value:</strong>
</td><td>
<div id="currentItem"><img src=expand.png></img></div>

</td>
</tr>
</table>
</body>
</html>


Thanks,
Neil

sunfighter
01-23-2011, 02:58 AM
When you use "innerHTML" your referencing text and you do not have text, you have an image.

try this:

<html>
<head>
<script type="text/javascript">
function toggleValue()
{
if (document.getElementById("currentItem").getAttribute("src") == "FireMaking.png")
{
document.getElementById("currentItem").setAttribute("src","Farming.png");
}else{
document.getElementById("currentItem").setAttribute("src","Fishing.png");
}
}
</script>
</head>
<body>
<table width =" 200" border="1">
<tr>
<td style="text-align: center;" colspan=2>
<input type="button" value="Toggle Value" onclick="toggleValue()">
</td>
</tr>
<tr>
<td>
<strong>Value:</strong>
</td>
<td style="text-align: center;">
<img id="currentItem" src="FireMaking.png" alt="">
</td>
</tr>
</table>
</body>
</html>

jmrker
01-23-2011, 03:24 AM
Why are you starting a new thread when you have yet to resolve the same question
at: http://www.codingforums.com/showthread.php?t=214165
which has described the problem for you already?
:confused:

venegal
01-23-2011, 04:13 AM
innerHTML doesn't give you the exact HTML source by the letter, because for it to work, it has to be parsed first. In your example, the wrong HTML source (<img> with closing tag) is parsed to correct HTML for innerHTML, that's why they are not the same. But even if your HTML would be correct: Comparing parsed to unparsed values is just wrong and won't work.

There are many right ways to do this, one of which is just changing the src, like sunfighter suggested.

Also, for further questions use the thread you already got. I'm closing this.