-2

I want to empty the innerText of an element. Wondering if it's better practice to set the innerText to null or ''. Any thoughts?

Ralph David Abernathy
  • 5,230
  • 11
  • 51
  • 78

2 Answers2

3
  • Use textContent, not innerText.
    • innerText is non-standard and originates with Internet Explorer and has some ill-defined behaviour, though all major browsers support it.
    • textContent is standard and is more rigidly defined, hence why it should be preferred.

The IDL for DOM's textContent describes it as a non-nullable DOMString, so any null JavaScript string value will be converted to an empty-string by the browser.

So it doesn't matter.

Dai
  • 141,631
  • 28
  • 261
  • 374
  • 1
    It's standard since 2016, see https://stackoverflow.com/questions/35213147/difference-between-textcontent-vs-innertext – Barmar Dec 09 '20 at 19:31
  • 1
    @Barmar Wow, TIL! Thank you. Here's the spec reference: https://html.spec.whatwg.org/multipage/dom.html#the-innertext-idl-attribute - though I can only find it on WHATWG rather than in the W3C's IDL. – Dai Dec 09 '20 at 19:34
  • But there are indeed a number of differences, as summarized in the linked question. – Barmar Dec 09 '20 at 19:55
2

It should do the same thing because it probably checks internally for a null argument and turns it into an empty string, but using '' would be better (since it would be better understood what you're trying to do with that).

Ethicist
  • 791
  • 2
  • 7
  • 23