JSFiddle - React, Tailwind, and code Playground

by erick

HTML

<div class="wrapper">
  <input type="button" value="ADD" onclick="append(1);">
</div>
<div class="templates" id="temp1">
  <ul class="level1">
    <li>
      <input placeholder="parent">
      <button onclick="append(2, this)">ADD</button>
      <button onclick="remove_div(this)">DEL</button>
    </li>
  </ul>
</div>
<div class="templates" id="temp2">
  <ul class="level2">
    <li>
      <input placeholder="child">
      <button onclick="append(3, this)">ADD</button>
      <button onclick="remove_div(this)">DEL</button>
    </li>
  </ul>
</div>
<div class="templates" id="temp3">
  <ul class="level3">
    <li>
      <input placeholder="sub-child">
      <button onclick="remove_div(this)">DEL</button>
    </li>
  </ul>
</div>

CSS

.templates { display: none; }

ul {
  background: rgba(255, 255, 255, 0.75);
  width: 200px;
  margin: 8px 0;
  padding-top: 4px;
  padding-bottom: 4px;
}

.level1 { border: 2px solid #f88; }
.level2 { border: 2px solid #8f8; }
.level3 { border: 2px solid #88f; }

JavaScript

function append(level, elm) {
  if (!elm) elm = document.body;
  else elm = elm.closest('ul');
  var appended = document.querySelector('#temp' + level).children[0].cloneNode(true);
  elm.appendChild(appended);
}

function remove_div(button) {
  var elm = button.closest("ul");
  elm.parentNode.removeChild(elm);
}