Explain Codes LogoExplain Codes Logo

Converting a javascript string to a html object

javascript
html-object
dom-manipulation
template-literals
Alex KataevbyAlex Kataev·Aug 20, 2024
TLDR

No time? Got it. Here’s your quick one-liner:

const str = '<div>HTML content</div>'; const htmlObject = new DOMParser().parseFromString(str, 'text/html').body.firstChild;

In this snippet, we 'magic' an HTML element out of your string. Ok, it's not actual magic, but DOMParser.

From simple to complex: different methods

The example above applies to complex HTML strings, but simple text content can be created using basic createTextNode:

const textStr = 'Unicorn tears'; // Yeah, we're making unicorns cry... const textNode = document.createTextNode(textStr); document.body.appendChild(textNode); // ...and proudly displaying those tears!

It doesn't allow HTML parsing, so no XSS hazards here!

Let's turn an HTML string with nodes and attributes into manipulatable object:

  1. Create magic container:

    var container = document.createElement('div');
  2. Fill it with sparkles:

    container.innerHTML = '<p>Fairy dust</p>';
  3. Now showcase those sparkles:

    var newElement = container.firstChild; document.body.appendChild(newElement);

Dynamics 101: Adding values on the fly

With template literals, you can play Merlin and inject magic into your HTML strings:

const mythicalCreature = 'Dragon'; const message = `<div>${mythicalCreature}, breathe fire!</div>`; container.innerHTML = message;

The stylist of DOM

Call upon the style property to transform that element’s attire:

newElement.style.marginTop = '10px'; // New height: Now you're tall as a hobbit! newElement.style.color = 'blue'; // Feeling blue? Time for a wardrobe change!

jQuery: Your magic wand

If you've got jQuery, you're halfway there:

const $htmlObject = $('<div>').html('<p>Wizardry with jQuery</p>'); $('body').append($htmlObject);

The enchanting $htmlObject stands as a manipulatable HTML element in the jQuery realm.

Watch out for the cursed spells

If your element has an ID:

  • Append the element to the DOM before summoning it with getElementById.
  • Beware of issues if the ID is not unique within the document.

Try the spell yourself

Go ahead and give it a go with our interactive wizardry lab: String to HTML Object Conversion

The object: your new pet dragon

After transforming your JavaScript string into an HTML object, it's yours to command:

  • Send it into battle:

    newElement.addEventListener('click', (e) => { console.log('Slayed!'); });
  • Adorn it with jewelry:

    newElement.setAttribute('data-custom', 'value');

Your dragon's companions

If your string breeds multiple nodes, you can call on each one:

const minions = Array.from(htmlObject.children); minions.forEach((minion) => { // Command each minion... });