How can I implement prepend and append with regular JavaScript?

Yosef picture Yosef · Aug 2, 2010 · Viewed 137.3k times · Source

How can I implement prepend and append with regular JavaScript without using jQuery?

Answer

Pat picture Pat · Aug 2, 2010

Here's a snippet to get you going:

theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';

// append theKid to the end of theParent
theParent.appendChild(theKid);

// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);

theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.