How do I change the text of a span element using JavaScript?

user105033 picture user105033 · Aug 31, 2009 · Viewed 648.7k times · Source

If I have a span, say:

<span id="myspan"> hereismytext </span>

How do I use JavaScript to change "hereismytext" to "newtext"?

Answer

Gregoire picture Gregoire · Aug 31, 2009

For modern browsers you should use:

document.getElementById("myspan").textContent="newtext";

While older browsers may not know textContent, it is not recommended to use innerHTML as it introduces an XSS vulnerability when the new text is user input (see other answers below for a more detailed discussion):

//POSSIBLY INSECURE IF NEWTEXT BECOMES A VARIABLE!!
document.getElementById("myspan").innerHTML="newtext";