How can I implement prepend and append with regular Javascript without using jQuery?
+2
A:
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.
Pat
2010-08-02 20:47:01
Thanks, why for prepend just use insertBefore without create additional div? like Grumdrig answer?
Yosef
2010-08-02 21:47:11
Grumdrig is right on this one. Edited with the fix.
Pat
2010-08-02 22:17:17
+1
A:
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.
Munzilla
2010-08-02 20:58:22