Converting a javascript string to a html object
No time? Got it. Here’s your quick one-liner:
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
:
It doesn't allow HTML parsing, so no XSS hazards here!
Let's turn an HTML string with nodes and attributes into manipulatable object:
-
Create magic container:
-
Fill it with sparkles:
-
Now showcase those sparkles:
Dynamics 101: Adding values on the fly
With template literals, you can play Merlin and inject magic into your HTML strings:
The stylist of DOM
Call upon the style
property to transform that element’s attire:
jQuery: Your magic wand
If you've got jQuery, you're halfway there:
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:
-
Adorn it with jewelry:
Your dragon's companions
If your string breeds multiple nodes, you can call on each one:
Was this article helpful?