How to add div dynamically inside a div using jQuery. It should display first also?

97,462

Solution 1

make use of jquery function .prepend() : Insert content, specified by the parameter, to the beginning of each element in the set of matched elements

$('Selector ').prepend($('<div> new div </div>'));

Solution 2

use prepend instead of append:

$("#parent").prepend("<div id='page_number'> You are watching 5th object out of 100 </div>");

Solution 3

Use prepend() instead of append():

$("#parent").prepend(
    "<div id='page_number'> You are watching 5th object out of 100 </div>");

Solution 4

See $("#parent").append("") adds your div at the end of the selected element.... if you want to add your divs as the first child of the parent, try prepend...

$("#parent").prepend("");

Solution 5

As well as using the .prepend() command mentioned by the other answers you can also use the .prependTo() command:

$("<div id='page_number'>You are watching 5th object out of 100 </div>").prependTo("#parent");
Share:
97,462
DEVOPS
Author by

DEVOPS

Updated on February 15, 2020

Comments

  • DEVOPS
    DEVOPS over 4 years

    I have a parent div like this.

    <div id='parent'>
       <div id='child_1'>........</div>
       <div id='child_2'>........</div>
       <div id='child_3'>........</div>
       <div id='child_4'>........</div>
    </div>
    

    I want to add one div like this:

    <div id='page_number'> You are watching 5th object out of 100 </div>
    

    Inside parent div I'm using append to do like that.

    $("#parent").append("<div id='page_number'> You are watching 5th object out of 100 </div>");
    

    But its comming after child_4 th div. But I need to display it just below of child_1. It should come like this

    <div id='parent'>
       <div id='page_number'> You are watching 5th object out of 100 </div>
       <div id='child_1'>........</div>
       <div id='child_2'>........</div>
       <div id='child_3'>........</div>
       <div id='child_4'>........</div>
    </div>
    

    How can I do like this.