Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 858
DEVOPS Avatar asked Feb 16 '12 09:02

DEVOPS


People also ask

How to add div inside Another div in jQuery?

Method 2: Using appendTo() Method: The appendTo() method in jQuery is used to insert HTML element at the end of the selected element. Example 1: This example uses appendTo() method to create div element at the end of selected element.

How to append a div using jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How can you add new DIV elements dynamically?

New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.

How dynamically add HTML element using jQuery?

$(document). ready(function() { $('body'). on('click', '. AddEl', function() { var $elems = $('.


3 Answers

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>')); 
like image 152
Pranay Rana Avatar answered Sep 28 '22 05:09

Pranay Rana


use prepend instead of append:

$("#parent").prepend("<div id='page_number'> You are watching 5th object out of 100 </div>"); 
like image 25
Hadas Avatar answered Sep 28 '22 03:09

Hadas


Use prepend() instead of append():

$("#parent").prepend(
    "<div id='page_number'> You are watching 5th object out of 100 </div>");
like image 40
Frédéric Hamidi Avatar answered Sep 28 '22 05:09

Frédéric Hamidi