How to best create a fake HTMLElement for mocking in unit tests and why does not DOMParser/Document.parseHTMLUnsafe work and only return HTMLDocument?

2 weeks ago 19
ARTICLE AD BOX
const realHtmlElement = document.getElementById('realHtmlElement'); console.log("realHtmlElement instanceof", typeof realHtmlElement, realHtmlElement instanceof HTMLElement) // => true const legacyDomParser = (new DOMParser()).parseFromString('<div id="thing">Text</div>', 'text/html'); console.log("legacyDomParser instanceof", typeof legacyDomParser, legacyDomParser instanceof HTMLElement) // => will be HTMLDocument instead and false const legacyDomParserGetElementById = (new DOMParser()).parseFromString('<div id="thing">Text</div>', 'text/html').getElementById('thing'); console.log("legacyDomParserGetElementById instanceof", typeof legacyDomParserGetElementById, legacyDomParserGetElementById instanceof HTMLElement) // => true const htmlDoc = Document.parseHTMLUnsafe('<div id="thing">Text</div>'); console.log("htmlDoc instanceof", typeof htmlDoc, htmlDoc instanceof HTMLElement) // => will be HTMLDocument instead and false const elementById = Document.parseHTMLUnsafe('<div id="thing">Text</div>').getElementById('thing'); console.log("elementById instanceof", typeof elementById, elementById instanceof HTMLElement) // => true <div id="realHtmlElement"></div>

What is the best approach here? Is getElementById the best solution or can we maybe get a HTML element (= a "real" HTMLElement) more easily?

Read Entire Article