Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I have a span, say:

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

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

like image 915
user105033 Avatar asked Aug 31 '09 18:08

user105033


People also ask

How do you update the text within an element using JavaScript?

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.

How do you change the text of an element?

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.

How do you style a span tag in HTML?

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.

Can you use span in JavaScript?

You can use the HTML span tag as a container to group inline elements together so you can style or manipulate them with JavaScript.


2 Answers

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"; 
like image 81
Gregoire Avatar answered Sep 21 '22 23:09

Gregoire


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.

like image 25
nicooo. Avatar answered Sep 20 '22 23:09

nicooo.