Home > database >  InnerHTML for null vs undefined
InnerHTML for null vs undefined

Time:04-28

Consider this snippet

const div = document.createElement('div');
div.innerHTML = null; // 1
console.log(`After setting null: "${div.innerHTML}"`);
div.innerHTML = undefined; // 2
console.log(`After setting undefined: "${div.innerHTML}"`);

Why doesn't the first snippet of innerHTML yield "null"? I expected the value to be a result of innerHTML = value to be same as String(value) as it expects a DOMString? String(null) yields "null".

MDN also mentions the ToString approach which too returns "null". The only thing that might hint at this special behavior is this snippet from the page on DOMString

Certain Web APIs accepting a DOMString have an additional legacy behavior, where passing null stringifies to the empty string instead of the usual "null".

Are there any definitive places (spec or otherwise) where such behavior can be confirmed from?

CodePudding user response:

Yes, there is a spec: https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin

innerHTML has the "IDL extended attribute" LegacyNullToEmptyString which describes this behavior.

  • Related