Cross-browser innerText for setting values
cross-browser, html, innertext, javascript
Solution
Instead of multiple assignments, you can grab the property and use that
var text = ('innerText' in d)? 'innerText' : 'textContent';
d[text] = 'New text';
Problem
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?