SO-38672923

by David Thomas

HTML

<p>In next example we can add new child element to this list:</p>
<ol id="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ol>
<button>Add new li-element to this list</button>
<p>In next example we can add new child element to this div:</p>
<div id="someThing">Something here</div>
<button>Add new div-element to this div</button>

CSS

div {
  border: 2px solid #eeeeee;
  background-color: #dff0d8;
}

ol {
  background-color: #dff0d8;
}

li {
  background-color: #eff0c8;
}

JavaScript

//
//
function derive(needle) {
  if (needle.nodeType && needle.nodeType === 1) {
    needle = [needle];
  } else if ('string' === typeof needle && document.getElementById(needle)) {
    needle = [document.getElementById(needle)];
  } else if ('string' === typeof needle && document.querySelectorAll(needle)) {
    needle = Array.from(document.querySelectorAll(needle));
  }

  return needle;
}

function addNewElement(opts) {

  var settings = {
      'append': true,
      'classes': null,
      'create': null,
      'content': 'Newly-added element.',
      'count': 1,
      'parent': document.body,
      'sibling': null
    },
    appendCheck,
    parents,
    childType,
    created,
    sibling,
    clone,
    classes,
    count,
    fragment = document.createDocumentFragment();

  Object.keys(opts || {}).forEach(function(key) {
    settings[key] = opts[key];
  });

  parents = derive(settings.parent);
  appendCheck = settings.append === true;
  count = parseInt(settings.count, 10);

  parents.forEach(function(pater) {
    childType = settings.create || (pater.children.length > 0 ? pater.lastElementChild.localName : null) || 'div';
    created = document.createElement(childType);
    if (appendCheck === true) {
      sibling = settings.sibling || pater.lastElementChild || pater.lastChild;
    } else if (appendCheck === false) {
      sibling = settings.sibling || pater.firstElementChild || pater.firstChild
    }

    created.innerHTML = settings.content;

    if (settings.classes) {
      classes = Array.isArray(settings.classes) ? settings.classes : settings.classes.split(/\s+/);
      classes.forEach(function(cN) {
        created.classList.add(cN);
      });
    }

    for (var i = 0; i < count; i++) {
      clone = created.cloneNode(true);
      fragment.appendChild(clone);
    }

    pater.insertBefore(fragment, (appendCheck ? sibling.nextSibling : sibling));
  });
}

var buttons =...