How can I implement prepend and append with regular JavaScript?
How can I implement prepend and append with regular JavaScript without using jQuery?
Solution 1:
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.
Solution 2:
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)
.
Solution 3:
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 to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
Solution 4:
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML
, with appropriate first argument:
'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.
Hint: you can always call Element.outerHTML
to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML
does not preserve listeners that where attached with .addEventLisntener
.