72

In a webpage I am calling a WebService that gives me an integer value. I need to display this value in a block of text. I am currently using an HTML <span>.

So far, I've found two methods of putting my value in a span. innerText() is an IE proprietary way of doing it and innerHTML() is a non-standards compliant way, although widely supported.

What is the correct standards compliant way of setting the text between <span> and </span> from Javascript?

Brian Beckett
  • 4,742
  • 6
  • 33
  • 52
  • 6
    As of HTML5, `innerHTML` **is** a part of the Spec http://dev.w3.org/html5/spec/Overview.html#innerhtml and supported by all browsers (minus *some* issues in IE (of all browsers) with the *setter* on `table` and `select` elements/sub-elements) – scunliffe Jan 24 '11 at 17:03

4 Answers4

76

With modern browsers, you can set the textContent property, see Node.textContent:

var span = document.getElementById("myspan");
span.textContent = "some text";
robinst
  • 30,027
  • 10
  • 102
  • 108
67

This is standards compliant and cross-browser safe.

Example: http://jsfiddle.net/kv9pw/

var span = document.getElementById('someID');

while( span.firstChild ) {
    span.removeChild( span.firstChild );
}
span.appendChild( document.createTextNode("some new content") );
user113716
  • 318,772
  • 63
  • 451
  • 440
23

To do it without using a JavaScript library such as jQuery, you'd do it like this:

var span = document.getElementById("myspan"),
    text = document.createTextNode(''+intValue);
span.innerHTML = ''; // clear existing
span.appendChild(text);

If you do want to use jQuery, it's just this:

$("#myspan").text(''+intValue);
Brian Donovan
  • 8,274
  • 1
  • 26
  • 25
  • 8
    You can just do `.text(intValue)`. The forced string conversion by concatenation isn't necessary. – chaos Jan 24 '11 at 16:52
3

The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).

The way I would actually do it is to use jQuery's .text().

chaos
  • 122,029
  • 33
  • 303
  • 309