Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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?

like image 230
StaticVariable Avatar asked Dec 27 '22 22:12

StaticVariable


2 Answers

$("<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:

  • after()

  • .before()

  • .insertBefore()

like image 103
thecodeparadox Avatar answered Jun 12 '23 15:06

thecodeparadox


$("#main").find(".mydiv").before("#yourDivToBeInserted");
like image 43
marius_5 Avatar answered Jun 12 '23 15:06

marius_5