If I have a span, say:
<span id="myspan"> hereismytext </span>
How do I use JavaScript to change "hereismytext" to "newtext"?
Use the textContent property to change the text of a div element, e.g. div. textContent = 'Replacement text' . The textContent property will set the text of the div to the provided string, replacing any of the existing content.
Use the textContent property to change the text of an element, e.g. element. textContent = 'New text' . The textContent property will set the text of the element to the provided string, replacing any of the existing content.
The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute. The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an inline element.
You can use the HTML span tag as a container to group inline elements together so you can style or manipulate them with JavaScript.
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";
Using innerHTML is SO NOT RECOMMENDED. Instead, you should create a textNode. This way, you are "binding" your text and you are not, at least in this case, vulnerable to an XSS attack.
document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!
The right way:
span = document.getElementById("myspan"); txt = document.createTextNode("your cool text"); span.appendChild(txt);
For more information about this vulnerability: Cross Site Scripting (XSS) - OWASP
Edited nov 4th 2017:
Modified third line of code according to @mumush suggestion: "use appendChild(); instead".
Btw, according to @Jimbo Jonny I think everything should be treated as user input by applying Security by layers principle. That way you won't encounter any surprises.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With