How can I implement prepend and append with regular JavaScript?
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 theParenttheParent.appendChild(theKid);// prepend theKid to the beginning of theParenttheParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild
will give us a reference to the first element within theParent
and put theKid
before it.
Perhaps you're asking about the DOM methods appendChild
and insertBefore
.
parentNode.insertBefore(newChild, refChild)
Inserts the node
newChild
as a child ofparentNode
before the existing child noderefChild
. (ReturnsnewChild
.)If
refChild
is null,newChild
is added at the end of the list of children. Equivalently, and more readably, useparentNode.appendChild(newChild)
.
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?If so here's how you can do it pretty easily:
//get the target div you want to append/prepend tovar someDiv = document.getElementById("targetDiv");//append textsomeDiv.innerHTML += "Add this text to the end";//prepend textsomeDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.