How to insert an element as the first child?

I want to add a div as the first element using jquery every time I click a button

<div id='parent-div'> <!--insert element as a first child here ...--> <div class='child-div'>some text</div> <div class='child-div'>some text</div> <div class='child-div'>some text</div> </div> 
+60
jquery css-selectors prepend
Dec 24 '10 at 18:59
source share
8 answers

Try the $.prepend() function.

Using

 $("#parent-div").prepend("<div class='child-div'>some text</div>"); 

Demo

 var i = 0; $(document).ready(function () { $('.add').on('click', function (event) { var html = "<div class='child-div'>some text " + i++ + "</div>"; $("#parent-div").prepend(html); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="parent-div"> <div>Hello World</div> </div> <input type="button" value="add" class="add" /> 
+109
Dec 24 '10 at 19:02
source share
— -

Usage: $("<p>Test</p>").prependTo(".inner"); Check out . Prepare documentation at jquery.com

+7
Feb 12
source share
 parentNode.insertBefore(newChild, refChild) 

Inserts node newChild as a child of parentNode before an existing child of node refChild. (Returns newChild.)

If refChild is null, newChild is added at the end of the list of children. Equivalent and more readable, use parentNode.appendChild (newChild).

+5
May 14 '14 at 4:36
source share

Continuing with what @vabhatia said, this is what you want in native JavaScript (without jQuery).

ParentNode.insertBefore(<your element>, ParentNode.firstChild);

+5
Jun 16 '15 at 8:48
source share
 parentElement.prepend(newFirstChild); 

This is a new addition (most likely) to ES7. This is now JS vanilla, probably due to its popularity in jQuery. It is currently available in Chrome, FF, and Opera. Transporters should be able to handle it until it is available everywhere.

PS You can directly add lines

 parentElement.prepend('This text!'); 

Links: developer.mozilla.org - Polyfill

+1
May 08 '17 at 12:26 a.m.
source share

$(".child-div div:first").before("Your div code or some text");

0
Mar 11 '14 at 11:51
source share
 $('.parent-div').children().before("<div class='child-div'>some text</div>"); 
0
Mar 14 '14 at 9:50
source share

Required here

<div class="outer">Outer Text <div class="inner"> Inner Text</div> </div>

added

$(document).ready(function(){ $('.inner').prepend('<div class="middle">New Text Middle</div>'); });

0
Aug 05 '15 at 7:57
source share



All Articles