Cross-browser innerText for setting values

Viewed 8063

Let's say I have the following code:

<html>
  <head></head>
  <body>
   <div id="d">some text</div>

  <script type="text/javascript">
    var d = document.getElementByid('d');
    var innerText = d.innerText || d.textContent;

    innerText = 'new text';
  </script>
  </body>
</html>

And I want to change text value for the div tag with id='d'. Unfortunately the block code above doesn't work and the text content doesn't change.

It works if do the following recipe:

if (d.innerText) d.innerText = 'new text';
else d.textContent = 'new text';

But I dont like the recipe above because it's not compact.

Have you any suggestions why the first approach doesn't work?

4 Answers
Related