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?
This question is related to
javascript
dhtml
html
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);
With modern browsers, you can set the textContent
property, see Node.textContent:
var span = document.getElementById("myspan");
span.textContent = "some text";
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()
.
Source: Stackoverflow.com