Skip to content

Instantly share code, notes, and snippets.

@julianlam
Created August 15, 2023 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianlam/bb6008e0c0eb0c8f8f0f81bd3eb6319b to your computer and use it in GitHub Desktop.
Save julianlam/bb6008e0c0eb0c8f8f0f81bd3eb6319b to your computer and use it in GitHub Desktop.
Inserting an HTML string to the DOM #blog

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;

container.append(...html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment