Changing the text of a label in javascript does not work

advertisements

I am trying to change the text of a Label using javascript like this in an aspx page

document.getElementById('DetailSection_EssLabel1').Text = "Revised Date";

But when I am in the debugging mode on IE by using F12 button, this is what I see for the field,

<SPAN class=FormFieldHeader        id=DetailSection_EssLabel1           Text="Revised Date">Assigned Completion Date</SPAN>

Though the text is changed to Revised Date, it is still showing Assigned Completion Date in the front end. Can someone tell me what I am missing. Thanks


Neither innerText nor textContent are cross-browser compatible if you include IE 8 and older.

Using the jQuery text method is typically the easy button.

if jQuery is not an option, the most compatible way with pure DOM is to use text nodes, for example:

var outputDiv = document.getElementById('DetailSection_EssLabel1');
var childNodes = outputDiv.childNodes;
// nodeType == 3 is a text node
if (!(childNodes.length == 1 && childNodes[0].nodeType == 3)) {
    outputDiv.innerHTML = ''; // one way to clear any existing content
    outputDiv.appendChild(document.createTextNode(''));
}
outputDiv.childNodes[0].nodeValue = 'Revised Text';

Fiddle: https://jsfiddle.net/4m0wpjdo/1/

EDIT: I also wanted to mention that using innerHTML to inject text is really not a good idea. It's all too easy to forget to escape special characters when using this approach. This opens you up to incorrect display of the text at best and XSS attacks at worst (if user-supplied text is included).