Create an HTML element with JavaScript
DOM manipulation via JavaScript is one of the very reasons the language was created. Oftentimes, you'll want to create an element from a string without appending it to the document. This can be useful when you need to create an element in memory before adding it to the DOM.
Luckily, all you need is Document.createElement()
and Element.innerHTML
to achieve is. The first method creates a new element, while the second sets its inner HTML to the string you provide. Finally, you can use Element.firstElementChild
to return the element version of the string.
const createElement = str => { const el = document.createElement('div'); el.innerHTML = str; return el.firstElementChild; }; const el = createElement( `<div class="container"> <p>Hello!</p> </div>` ); console.log(el.className); // 'container' const other = createElement( `<p>Hi!</p> <div>Bye!</div>` ); console.log(other.tagName); // 'P' (only the first element is returned)