526

If I have a span, say:

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

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

isherwood
  • 58,414
  • 16
  • 114
  • 157
user105033
  • 18,800
  • 19
  • 58
  • 69

18 Answers18

863

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";
Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
Gregoire
  • 24,219
  • 6
  • 46
  • 73
  • how do you insert a style attribute into the `span` using javascript here? – bouncingHippo Sep 10 '12 at 15:32
  • 2
    @bouncingHippo document.getElementById("myspan").setAttribute("style","cssvalues"); – Gregoire Sep 11 '12 at 06:44
  • @Gregoire keep in mind that your solution doesn't work on ie8 at least. See http://stackoverflow.com/questions/2119300/setattribute-is-not-working-for-style-attribute-on-ie?lq=1 – MeTTeO Mar 13 '13 at 12:09
  • 3
    there should be some way of merging those two answers into one. its the exact same answer. – john-jones Feb 18 '14 at 11:47
  • 7
    This doesn't set the **text**, it sets the **HTML** which is fundamentally different. – Brad Oct 11 '14 at 02:05
  • 32
    @gregoire - As others have pointed out already your answer is vulnerable to XSS. This question has been viewed about 80k times already, which means that a lot of people have probably taken over this solution and might have introduced unnecessary xss leaks. Could you consider updating your answer to use `textContent` instead, such that new people will be encouraged to use proper and secure methods? – Tiddo Jan 20 '15 at 21:59
  • 3
    @Tiddo textContent is not supported in IE8 and below and I hope for you that you never use directly non sanitized user input in your script. – Gregoire Jan 21 '15 at 11:20
  • 2
    **Tip:** It doesn't hurt taking a look at the following blog entry: [The poor, misunderstood innerText](http://perfectionkills.com/the-poor-misunderstood-innerText/) Great article to get an idea about the differences between `.innerText` and `.textContent`, the performance and also what kinda happens 'behind the scenes'. Some important information is there, IMO. :) – Dennis98 Sep 30 '16 at 21:22
93

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.

nicooo.
  • 1,085
  • 8
  • 7
  • 6
    While you are absolutely correct about `innerHTML` requiring caution, note that your solution uses `innerText` which is not supported in Firefox. http://www.quirksmode.org/dom/html/ It also uses `textContent` which is not supported in IE8. You can structure code to get around these issues. – Trott Oct 02 '14 at 15:48
  • 4
    Use `span.appendChild(txt);` instead! – mumush Sep 03 '15 at 17:53
  • 38
    The question says nothing about user input, so a blanket statement that `innerHTML` is not recommended is ridiculous. Not to mention it is still fine once sanitized. The idea that one should sanitize user input is **SO NOT RELATED** to this specific question. At most it merits a small note at the end saying _"btw: if it's user input make sure to sanitize first or use X method that doesn't need it"_. – Jimbo Jonny Jan 23 '16 at 20:30
  • Plus, creating elements is WAY faster than using innerHTML. – Samuel Rondeau-Millaire Mar 23 '16 at 21:29
  • 4
    Using appendChild does not actually _change_ the text, it only adds to it. Using your code here, the span from the original question would end up reading "hereismytextyour cool text". Perhaps `span.innerHTML = "";` then appendChild? – ShaneSauce May 09 '18 at 16:45
  • 3
    @JimboJonny When speaking about questions such as this which have been viewed over 650,000 times, what the OP is specifically asking is utterly irrelevant. Therefore I do believe it is prudent to mention the XSS vulnerability prominently, in the interest of public safety. – yeah22 Mar 16 '21 at 07:14
40

EDIT: This was written in 2014. A lot has changed. You probably don't care about IE8 anymore. And Firefox now supports innerText.

If you are the one supplying the text and no part of the text is supplied by the user (or some other source that you don't control), then setting innerHTML might be acceptable:

// * Fine for hardcoded text strings like this one or strings you otherwise 
//   control.
// * Not OK for user-supplied input or strings you don't control unless
//   you know what you are doing and have sanitized the string first.
document.getElementById('myspan').innerHTML = 'newtext';

However, as others note, if you are not the source for any part of the text string, using innerHTML can subject you to content injection attacks like XSS if you're not careful to properly sanitize the text first.

If you are using input from the user, here is one way to do it securely while also maintaining cross-browser compatibility:

var span = document.getElementById('myspan');
span.innerText = span.textContent = 'newtext';

Firefox doesn't support innerText and IE8 doesn't support textContent so you need to use both if you want to maintain cross-browser compatibility.

And if you want to avoid reflows (caused by innerText) where possible:

var span = document.getElementById('myspan');
if ('textContent' in span) {
    span.textContent = 'newtext';
} else {
    span.innerText = 'newtext';
}
Trott
  • 66,479
  • 23
  • 173
  • 212
  • 2022 Update: For the people who might come across this answer, now `innerText` is supported in Firefox [see the Caniuse status](https://caniuse.com/innertext). So you can only use `innerText`. And also [check the MDM doc](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText) to see the differences between `innerText` and `textContent`. – Ben Souchet Mar 08 '22 at 12:36
  • @BenSouchet Thanks. I've updated the caveat that starts the answer to include the Firefox info. Feel free to edit further if you think it would be helpful to provide additional info and/or links to folks. – Trott Mar 08 '22 at 14:21
30
document.getElementById('myspan').innerHTML = 'newtext';
Nightfirecat
  • 11,432
  • 6
  • 35
  • 51
Dan
  • 797
  • 1
  • 7
  • 14
25

I use Jquery and none of the above helped, I don't know why but this worked:

 $("#span_id").text("new_value");
shellbye
  • 4,620
  • 4
  • 32
  • 44
10

Here's another way:

var myspan = document.getElementById('myspan');

if (myspan.innerText) {
    myspan.innerText = "newtext";
}
else
if (myspan.textContent) {
        myspan.textContent = "newtext";   
}

The innerText property will be detected by Safari, Google Chrome and MSIE. For Firefox, the standard way of doing things was to use textContent but since version 45 it too has an innerText property, as someone kindly apprised me recently. This solution tests to see if a browser supports either of these properties and if so, assigns the "newtext".

Live demo: here

slevy1
  • 3,797
  • 2
  • 27
  • 33
  • 1
    Firefox implemented innerText support in [release 45](https://developer.mozilla.org/en-US/Firefox/Releases/45). – user3351605 Sep 30 '16 at 19:21
7

In addition to the pure javascript answers above, You can use jQuery text method as following:

$('#myspan').text('newtext');

If you need to extend the answer to get/change html content of a span or div elements, you can do this:

$('#mydiv').html('<strong>new text</strong>');

References:

.text(): http://api.jquery.com/text/

.html(): http://api.jquery.com/html/

Mohamed Nagieb
  • 819
  • 9
  • 11
3

Many people still come across this question (in 2022) and the available answers are not really up to date.

Use innerText is the best method

As you can see in the MDM Docs innerText is the best way to retrieve and change the text of a <span> HTML element via Javascript.

The innerText property is VERY well supported (97.53% of all web users according to Caniuse)

How to use

Simple retrieve and set new text with the property like this:

let mySpan = document.getElementById("myspan");

console.log(mySpan.innerText);

mySpan.innerText = "Setting a new text content into the span element.";

Why better than innerHTML ?

Don't use innerHTML to updating the content with user inputs, this can lead to major vulnerability since the string content you will set will be interpreted and converted into HTML tags.

This means users can insert script(s) into your site, this is known as XSS attacks/vulnerabilities (Cross-site scripting).

Why better than textContent ?

First point textContent isn't supported by IE8 (but I think in 2022 nobody cares anymore). But the main element is the true difference of result you can get using textContent instead of innerText.

The example from the MDM documentation is perfect to illustrate that, so we have the following setup:

<p id="source">
  <style>#source { color: red;  } #text { text-transform: uppercase; }</style>
<span id=text>Take a look at<br>how this text<br>is interpreted
       below.</span>
  <span style="display:none">HIDDEN TEXT</span>
</p>

If you use innerText to retrieve the text content of <p id="source"> we get:

TAKE A LOOK AT
HOW THIS TEXT
IS INTERPRETED BELOW.

This is perfectly what we wanted.

Now using textContent we get:


  #source { color: red;  } #text { text-transform: uppercase; }
Take a look athow this textis interpreted
       below.
  HIDDEN TEXT

Not exactly what you expected...

This is why using textContent isn't the correct way.

Last point

If you goal is only to append text to a <p> or <span> HTML element, the answer from nicooo. is right you can create a new text node and append it to you existing element like this:

let mySpan = document.getElementById("myspan");

const newTextNode = document.createTextNode("Youhou!"),

mySpan.appendChild(newTextNode);
Ben Souchet
  • 1,450
  • 6
  • 20
2

You may also use the querySelector() method, assuming the 'myspan' id is unique as the method returns the first element with the specified selector:

document.querySelector('#myspan').textContent = 'newtext';

developer.mozilla

Addis
  • 2,480
  • 2
  • 13
  • 21
1

Like in other answer, innerHTML and innerText are not recommended, it's better use textContent. This attribute is well supported, you can check it this: http://caniuse.com/#search=textContent

Nammen8
  • 619
  • 1
  • 11
  • 31
0
document.getElementById("myspan").textContent="newtext";

this will select dom-node with id myspan and change it text content to new text

Jimi Pajala
  • 2,358
  • 11
  • 20
0

You can do

 document.querySelector("[Span]").textContent = "content_to_display"; 
trustidkid
  • 577
  • 4
  • 6
0

Can't be used with HTML code insertion, something like:
var a = "get the file <a href='url'>the link</a>"
var b = "get the file <a href='url'>another link</a>"
var c = "get the file <a href='url'>last link</a>"

using
document.getElementById("myspan").textContent=a;
on
<span id="myspan">first text</span>

with a timer but it just shows the reference target as text not runing the code, even tho it does shows correctly on the source code. If the jquery approch is not really a solution, the use of:

document.getElementById("myspan").innerHTML = a to c;
is the best way to make it work.

0

const span = document.querySelector("#span");
const btn = document.querySelector("#changeBtn");

btn.addEventListener("click", () => {
span.innerText = "text changed"
})
<span id="span">Sample Text</span>
<button id="changeBtn">Change Text</button>
Honey_G
  • 11
  • 2
-1

For this span

<span id="name">sdfsdf</span>

You can go like this :-

$("name").firstChild.nodeValue = "Hello" + "World";
Dhiraj Himani
  • 1,062
  • 12
  • 9
-1

(function ($) {
    $(document).ready(function(){
    $("#myspan").text("This is span");
  });
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myspan"> hereismytext </span>

user text() to change span text.

Rayees AC
  • 4,426
  • 3
  • 8
  • 31
-1

I used this one document.querySelector('ElementClass').innerText = 'newtext';

Appears to work with span, texts within classes/buttons

-1

For some reason, it seems that using "text" attribute is the way to go with most browsers. It worked for me

$("#span_id").text("text value to assign");

Qasim Bataineh
  • 687
  • 6
  • 3