Cross-browser innerText for setting values

Erik picture Erik · Jul 25, 2012 · Viewed 7.9k times · Source

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?

Answer

Gabriele Petrioli picture Gabriele Petrioli · Jul 25, 2012

Instead of multiple assignments, you can grab the property and use that

var text = ('innerText' in d)? 'innerText' : 'textContent';
d[text] = 'New text';