getHTML() — a superior alternative to innerHTML
innerHTML vs getHTML(). When modern getHTML() is more suitable and how it should be used?
With getHTML()
now supported by all browsers, it is time to use it. But what can getHTML()
do that innerHTML
cannot do?
getHTML()
does the same as the innerHTML
getter — it returns the HTML of the DOM tree inside the element. The returned HTML can be used to replicate the original DOM tree. The only difference between the two methods is that the newer one is potentially able to include HTML of shadow trees into the generated HTML, whereas innerHTML
always disregards shadow DOM.
To appreciate the additional capabilities of getHTML()
let’s use several simple web pages.
getHTML()
accepts an optional object options
and returns the complete HTML only when suitable options are provided:
The original shadow DOM is rendered in the complete HTML as declarative shadow roots. If the returned HTML <div><template shadowrootmode="open"><p>Paragraph <slot>default</slot></p></template>123</div>
is opened in a browser as a new page, the original DOM tree is…