Miscellaneous bits and bobs from the tech world

Inserting an HTML string to the DOM

8/15/2023, 11:47:00 AM

Question: How do you insert an HTML string (e.g. <p>this is a paragraph <a href="#">with an anchor!</a></p>) into the DOM?

It's easy with jQuery, $(htmlString). But what if you don't want to use jQuery? It's also pretty straightforward.

const container = document.getElementById('container');
let html = '<p>this is a paragraph <a href="#">with an anchor!</a></p>';
html = new DOMParser().parseFromString(html, 'text/html').body.childNodes;