views:

62

answers:

3

Without using any JavaScript frameworks, how do I dynamically change the text within a SPAN element.

I know how to do this with a DIV, it would be the following:

document.getElementById('myDiv').innerHTML = '...'

What's the equivalent of this for a SPAN element?

+2  A: 

That specific technique works for any element, though the caveat on using it on elements such as divs is that it will replace inner elements and not only text.

If you only want to replace the text you can do so by:

function replaceText( el, str ) {
    el.textContent ? el.textContent = str : el.innerText = str;
}

replaceText( spanReference, 'blah' )
meder
+2  A: 

Hi Timgoo,

getElementById() do exactly as the name implies: get an element with id attribute equals to argument; so, if you have an span named "mySpan", your code should be:

document.getElementById('mySpan').innerHTML = '...'
Rubens Farias
A: 

You can use innerHTML for span elements also.

What happened when you tried to do that?

For a brief example you can look at: http://bytes.com/topic/javascript/answers/149023-there-faster-way-change-span-innerhtml

James Black