2

I am trying to use javascript to update the text in a html label.

It works in all browsers except IE8. In IE8 the label appears to be updated but is not displayed on the screen.

I've created demo code below that shows the issue.

Thanks

<html>
 <head>
 <script>
  function sendRequest() {               
    document.getElementById('errormessage').textContent="test";
    alert("textContent : "+document.getElementById('errormessage').textContent);
  }   
</script>

</head>

<body>

  <a href="javascript:void(0)" onclick="sendRequest();"> Click me</a>
   <br/>
  <label id="errormessage" style="color:#F00">&nbsp;</label>
</body> 
</html>

2 Answers 2

2

IE 8 and under doesn't have textContent.

Try this:

function setText(el, text){
    if(typeof el.innerText !== 'undefined')
        el.innerText = text;
    else
        el.textContent = text;
}

function getText(el){
    return el.innerText || el.textContent;
}

function sendRequest() {
    var el = document.getElementById('errormessage');
    setText(el, "test");
    alert("textContent : "+getText(el));
}   
Sign up to request clarification or add additional context in comments.

1 Comment

The innerText and textContent properties are strings, therefore the typeof test should test for that, e.g. if (typeof el.textContent == 'string').
2
document.getElementById('errormessage').innerHTML="test";

3 Comments

Thanks. It seems to vary from browser to browser.
You could use jQuery, it should take care of browser inconsistencies.
Use jQuery to resolve browser inconsistencies in innerHTML? How?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.