Files
30-seconds-of-code/snippets/js/s/create-element.md
2023-05-07 16:07:29 +03:00

895 B

title, type, language, tags, cover, excerpt, dateModified
title type language tags cover excerpt dateModified
Create HTML element snippet javascript
browser
flower-portrait-4 Creates an element from a string without appending it to the document. 2020-10-19T18:51:03+03:00

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