PJ6 wrote:
"Randy Webb" <Hi************@aol.com> wrote in message
news:5o********************@comcast.com...
What types of "any element" that has a text property are you trying to
change?
ClassName.. thanks for pointing that out, I should have seen that. Maybe I
need some sleep.
Let's pick the one I'm working on at the moment. Is it possible to change
the text in a <SPAN> element client-side?
As suggested by Mick, innerHTML is likely best if you want to completely
replace the contents of the span and what you are putting in there is
either plain text or text with some minimal markup (say text with a few
<em> or <b> elements).
For completeness, you should know about the DOM methods too. If you
know that the span has one text node, and that is what you want to
replace, then:
theSpan.firstChild.data = 'some text';
will do the trick. If there are multiple text nodes, or other elements
to replace also, there's a bit more to it.
If you want to add a complex document fragment, using the document
object model (DOM) may be a better solution, even though it requires
more code. To remove the content of the element, you can use the quick
'n dirty:
theSpan.innerHTML = '';
or DOM:
while (theSpan.firstChild) {
theSpan.removeChild(theSpan.firstChild);
}
Now to add the text:
theSpan.appendChild(document.createTextNode('some new text'));
If you want to add part of a table (you wouldn't do that inside a span
element but you may want to use it elsewhere), then DOM is the only way
to go - innerHTML will likely fail in most browsers, including IE.
innerHTML has some other foibles, so use with caution for complex
situations and consider using DOM instead.
Here's some play code:
<p>The span follows: <span id="spanA">text to replace</span></p>
<input type="button" value="Replace text DOM" onclick="
var theSpan = document.getElementById('spanA');
theSpan.firstChild.data = 'DOM replacement text';
">
<br>
<input type="button" value="Replace text innerHTML" onclick="
var theSpan = document.getElementById('spanA');
theSpan.innerHTML = 'innerHTML replacement text';
">
<br>
<input type="button" value="Long DOM method" onclick="
var theSpan = document.getElementById('spanA');
while (theSpan.firstChild) {
theSpan.removeChild(theSpan.firstChild);
}
var txt = 'Long DOM replacement text'
theSpan.appendChild(document.createTextNode(txt));
">
--
Rob