tags:

views:

59

answers:

3

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
Thanks, why for prepend just use insertBefore without create additional div? like Grumdrig answer?
Yosef
Grumdrig is right on this one. Edited with the fix.
Pat
+1  A: 

I think perhaps you're asking about DOM methods appendChild and insertBefore. See here.

Grumdrig
+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