Create HTML element

JavaScript, Browser · Oct 19, 2020

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 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">
console.log(el.className); // 'container'

More like this

  • JavaScript DOM Manipulation

    Create, insert, remove and manipulate DOM elements with this collection of JavaScript tips and tricks.

    Collection · 6 snippets

  • Creating HTML elements in JavaScript

    Learn how to create HTML elements in JavaScript, by abstracting the creation logic into a function.

    JavaScript, Browser · May 29, 2022

  • Array to HTML list

    Converts the given array elements into <li> tags and appends them to the list of the given id.

    JavaScript, Browser · Oct 20, 2020

  • Insert HTML string after element

    Inserts an HTML string after the end of the specified element.

    JavaScript, Browser · Oct 20, 2020