Back to blog

Wrap an element with custom createElement in JavaScript

createElement function creates a wrapper element from a string. wrap function uses it to easily wrap a given element arround the wrapper string. The given wrapper can also be an HTMLElement.

const createElement = (value, doc = document) => {
    const element = doc.createElement("div");
    element.innerHTML = value;

    // we return only the first element
    return element.firstElementChild;

const wrap = (element, target) => {
  // element and target must be given to continue 
  if (!element || !target) return;

  let wrapper;

  // we give the possibility to wrap arround a given HTMLElement
  // otherwise we create it with `createElement` function
  if (typeof target === "object" && target.nodeType === 1) {
    wrapper = target;
  } else {
    wrapper = createElement(target);

  element.parentNode.insertBefore(wrapper, element);

  return wrapper;

Let’s assume that we have this HTML structure

<div class="container">
  <div class="toto">
    Hello from toto

We want to wrap what’s inside the div with toto class inside another div with titi class

const toto = document.querySelector(".toto");

// the wrapper can be an `HTMLElement`
wrap(toto, "<div class='titi'></div>")

Voilà 🎉

<div class="container">
  <div class="titi">
    <div class="toto">
      Hello from toto

Before you leave…
Thanks for reading! 😊