1

I have a div and i want to append another div inside it. but, by using appendChild() it always insert DOM element in end of container element.but i want to insert it in starting of container div.
How to achieve this ?

var newDiv= document.createElement('div');
newDiv.innerHTML = "<input type='text'/>";
var item = document.getElementById('containerDivId');
item.appendChild(newDiv);`
ѕтƒ
  • 3,547
  • 10
  • 47
  • 78
Sudarshan Tanwar
  • 3,537
  • 3
  • 24
  • 39

6 Answers6

8

prepend() is what u need..

Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

 item.prepend(newDiv);
bipen
  • 36,319
  • 9
  • 49
  • 62
3

Since you've included jquery tag... You can use prepend() method.

Or you could use pure JS insertBefore:

item.insertBefore(newDiv, item.firstChild);
strah
  • 6,702
  • 4
  • 33
  • 45
3

use 'item.insertBefore(newDiv, item.firstChild);'

1

You can use prepend function in jQuery. For example,

$(item).prepend(newDiv);
haitaka
  • 1,832
  • 12
  • 21
1

I think you find insertBefore.

parentElem.insertBefore(insertedElem, parentElem.firstChild);
kubedan
  • 616
  • 2
  • 7
  • 26
1

You can use prepend() on the parent element to add a child first.

http://api.jquery.com/prepend/

I don't have time to test it, but i think that will work.

var newDiv= document.createElement('div');
    newDiv.innerHTML = "<input type='text'/>";
var item = document.getElementById('containerDivId');
    item.prepend(newDiv);
strah
  • 6,702
  • 4
  • 33
  • 45
Millenjo
  • 461
  • 7
  • 16
  • 1
    Oh god, so many answers, sorry. Was empty when i started writing =) – Millenjo Feb 27 '13 at 11:12
  • As edited by Ajay, this works without jquery but i don't know how it reacts when the container has no children? And fyi, he tagged the question with jquery so the answer before the edit was valid as well. – Millenjo Feb 27 '13 at 11:55
  • I rolled back the answer to the original version, Ajay's edit was invalid (it changed too much, and was rather a comment) – strah Feb 27 '13 at 11:59
  • The code you posted is incorrect. `item` is a DOM element and does not have a method `.prepend`. – Felix Kling Jun 25 '13 at 19:26