StaticVariable
StaticVariable

Reputation: 5283

How to append something before a particular div with a random number

I want to append a div inside a div which have many divs inside itself. My code is shown below:

<div id="main">
<div class="random no"></div>
<div class="random no"></div>
<div class="random no"></div>
<div class="random no"></div>
<div class="mydiv"></div>
</div>

My jQuery code is:

$("#main").append("<div class='random no'> </div>");

But it appends after the last child of div "main". How to insert that div before #mydiv?

Upvotes: 4

Views: 1887

Answers (2)

marius_5
marius_5

Reputation: 501

$("#main").find(".mydiv").before("#yourDivToBeInserted");

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

$("<div class='random no'> </div>").insertBefore("#main .mydiv");

DEMO

or

$("#main .mydiv").before("<div class='random no'> </div>");

DEMO

or

$('#main').append("<div class='random no'> Random no</div>").after($(".mydiv"))​;

DEMO

Related refs:

Upvotes: 9

Related Questions