Explain Codes LogoExplain Codes Logo

Converting HTML string into DOM elements?

javascript
dom-parser
html-string
dom-elements
Anton ShumikhinbyAnton Shumikhin·Sep 21, 2024
TLDR

You can transform your HTML string into DOM elements using innerHTML like this:

const html = "<p>Example</p>"; const div = document.createElement("div"); // Create an empty container div.innerHTML = html; // Load the container with HTML const element = div.firstChild; // Voila! <p>Example</p> is a DOM node

The element is your newly created DOM node, ready for action.

DOMParser: Your handy HTML translator

Beyond innerHTML, an elegant tool called DOMParser is just what you need:

const htmlString = "<p>Example</p>"; const parser = new DOMParser(); // Create a new parser const doc = parser.parseFromString(htmlString, "text/html"); // Parse the string const element = doc.body.firstChild; // Just <p>Example</p> being a DOM node, no biggie

DOMParser is robust and secure. It gifts you a Document you can fondle just like your main document.

Spotting trouble: Security matters

Security is a priority, especially in user-generated content:

  • Phenomenon called XSS attacks? Prevent those. Sanitize inputs.
  • Setting text? Use textContent instead of innerHTML. Trust me, it's like wearing a spacesuit in a vacuum.
  • HTML strings about to be parsed? Wash it once, wash it twice, wash it thrice. Clean, clean, clean.

Meeting the special kids: HTML structural peculiarities

Some HTML structures are a bit fussier and require special parents. Let's handle table rows:

const tableHtml = "<tr><td>Example</td></tr>"; const table = document.createElement("table"); const tbody = document.createElement("tbody"); table.appendChild(tbody); tbody.innerHTML = tableHtml; const element = tbody.firstChild; // It's a <tr>! I’m not crying, you’re crying

Not all HTML elements are made equal, so use right parent tags for correctness.

insertAdjacentHTML: The heavyweight champion

Make room! insertAdjacentHTML could be your new favourite tool:

// targetElement is that stubborn sibling you are trying to work with targetElement.insertAdjacentHTML(position, htmlString);

Where is that position you ask? Well, it can be beforebegin, afterbegin, beforeend, or afterend. Yes, English!

Rethinking containers: <template> elements

The <template> tag is the invisible magician that only shows its trick when cloned and inserted:

<template id="sample"> <p>Non-rendered content</p> </template> <script> const content = document.querySelector('#sample').content; document.body.appendChild(content.cloneNode(true)); </script>

Extra tips & pitfalls on the road

Knowledge is power, but practical tips are superpowers:

  • Dynamic content loading: These methods come in handy. Fetch data via AJAX, parse, insert, win the internet.
  • Template processing: Parse and fill the blanks on templates before injecting them into the DOM.
  • Script tags: In a HTML string loaded via innerHTML, scripts ain't gonna run. DOMParser preserves script tags but doesn't run them.
  • Browser compatibility: Yes, not all browsers play along. Check the support and slap a polyfill if necessary.