Forum Moderators: open
Here is my code:
<html>
<head>
</head>
<body>
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td>
<p id="example3">I want to replace this text: <span id="ex3Span">right here </span>.</p>
<script type="text/javascript">function replaceSpan(TheId,lvl)
{
if ( lvl == '1') {
newText = "Sentence relating to option 1";
} else if ( lvl == '2' ) {
newText = document.createTextNode("Sentence relating to option 1");
} else if ( lvl == '3' ) {
newText = document.createTextNode("Sentence relating to option 2");
} else if ( lvl == '4' ) {
newText = document.createTextNode("Sentence relating to option 3");
}
var newSpan = document.createElement("span");
newSpan.appendChild(newText);
var para = document.getElementById("example3");
var spanElm = document.getElementById("ex3Span");
var replaced = para.replaceChild(newSpan,spanElm);
}
</script>
<SELECT NAME = "option¦3¦7" id="option¦3¦7" onChange="replaceSpan(this.id,this.options[this.selectedIndex].value);">
<OPTION VALUE = "1">Choose option
<OPTION VALUE = "2">Option 1
<OPTION VALUE = "3">Option 2
<OPTION VALUE = "4">Option 3
</SELECT>
</td>
</tr>
</table>
</body>
</html>
I'm assuming the problem is that the newly created span does not maintain the ID of the old one. If that is so, how can I assign an ID when the new span is created?
/*! sent 'this.selectedIndex' as parameter in call */
function replaceSpan(lvl)
{
// An array is easier to edit.
// Here it's defined and used at the same time.
var text =
[
"Sentence relating to option 1",
"Sentence relating to option 2",
"Sentence relating to option 3"/**/
][lvl-1];var span = document.getElementById("ex3Span");
while(span.childNodes[0]) /* removing nodes */
span.removeChild(span.childNodes[0]);
span.appendChild(document.createTextNode(text));
}
I thought it would be easier to change the contents of the span, rather than replacing the span itself. innerHTML is easy, but as you're going for pure DOM...
Unsafe to assume there's only one child text node, so we remove the first until there are no more.