How to append and prepend using JavaScript?

We can do the append and prepend in JavaScript very easily. In fact, other libraries that have quite a simple method to use append and prepend use native JavaScript appendChild and insertBefore methods:

  parentElement = document.getElementById("#content");
  childElement = document.createElement("div");
  childElement.innerHTML = 'Inner content';

  // append example
  parentElement.appendChild(childElement);

  // prepend example
  parentElement.insertBefore(childElement, parentElement.firstChild);
Share