JavaScript, Browser

Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.

  • Use Document.createElement() to create a new element.
  • Use Element.innerHTML to set its inner HTML to the string supplied as the argument.
  • Use ParentNode.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">
console.log(el.className); // 'container'

Recommended snippets

  • listenOnce

    JavaScript, Browser

    Adds an event listener to an element that will only run the callback the first time the event is triggered.

  • getURLParameters

    JavaScript, Browser

    Creates an object containing the parameters of the current URL.

  • getSiblings

    JavaScript, Browser

    Returns an array containing all the siblings of the given element.