PJ6 wrote:
"Randy Webb" <Hi************ @aol.com> wrote in message
news:5o******** ************@co mcast.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.firstCh ild.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.innerHT ML = '';
or DOM:
while (theSpan.firstC hild) {
theSpan.removeC hild(theSpan.fi rstChild);
}
Now to add the text:
theSpan.appendC hild(document.c reateTextNode(' 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">tex t to replace</span></p>
<input type="button" value="Replace text DOM" onclick="
var theSpan = document.getEle mentById('spanA ');
theSpan.firstCh ild.data = 'DOM replacement text';
">
<br>
<input type="button" value="Replace text innerHTML" onclick="
var theSpan = document.getEle mentById('spanA ');
theSpan.innerHT ML = 'innerHTML replacement text';
">
<br>
<input type="button" value="Long DOM method" onclick="
var theSpan = document.getEle mentById('spanA ');
while (theSpan.firstC hild) {
theSpan.removeC hild(theSpan.fi rstChild);
}
var txt = 'Long DOM replacement text'
theSpan.appendC hild(document.c reateTextNode(t xt));
">
--
Rob