Set HTML <span> Content Using Javascript

On the webpage, I call WebService, which gives me an integer value. I need to display this value in a block of text. I am currently using HTML <span> .

So far, I have found two methods for entering my value in between. innerText() is a proprietary way of IE, and innerHTML() is a non-standard way, although it is widely supported.

What is the correct way to match text between <span> and </span> from Javascript?

+43
javascript html dhtml
Jan 24 '11 at 16:45
source share
4 answers

It is a standards compliant and cross browser.

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

 var span = document.getElementById('someID'); while( span.firstChild ) { span.removeChild( span.firstChild ); } span.appendChild( document.createTextNode("some new content") ); 
+49
Jan 24 '11 at 17:06
source share

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

 var span = document.getElementById("myspan"); span.textContent = "some text"; 
+28
Apr 9 '14 at 2:03
source share

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

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

If you want to use jQuery, this is simple:

 $("#myspan").text(''+intValue); 
+17
Jan 24 2018-11-11T00:
source share

The most appropriate way to standards is to create a text node containing the desired text and add it to the range (delete any existing existing text nodes).

How I would do this is to use jQuery .text() .

+1
Jan 24 '11 at 16:50
source share



All Articles