John
John

Reputation: 627

How do I insert a new div before the last div using jQuery?

<div id="one">test test</div>
<div id="two">test test</div>
<div id="three">test test</div>
<div id="four">test test</div>
<div id="five">test test</div>

If I want to insert a div dynamically with jQuery in between divs "four" and "five", how would I go about doing that?

I tried this but it didn't work:

$("<div id='four-point-five'></div>").before("#five");

Upvotes: 2

Views: 301

Answers (8)

abhishek ameta
abhishek ameta

Reputation: 194

use this

>  $("#five").before( " <div id='four-point-five'> </div> " );

Upvotes: 2

IvenMS
IvenMS

Reputation: 535

Please try this:

$("#five").before("<div id='four-point-five'></div>");

Upvotes: 1

Ayman Safadi
Ayman Safadi

Reputation: 11552

Try this: http://jsfiddle.net/gNQwR/

$("<div>").attr('id', 'four-point-five').text('test 4.5').insertBefore("#five");

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150010

Try this:

$("<div id='four-point-five'></div>").insertBefore("#five");

// OR

$("#five").before("<div id='four-point-five'></div>");

The problem is that you didn't read the doco the .before() method expects the existing element as the $() selector and the new content as the parameter. The .insertBefore() method works the other way around.

Upvotes: 2

Abdul Munim
Abdul Munim

Reputation: 19217

Try this:

$("<div id='four-point-five'></div>").insertAfter("#four");

Upvotes: 2

Ricardo Souza
Ricardo Souza

Reputation: 16446

$("#five").before("<div id='four-point-five'></div>")

Upvotes: 2

Matt
Matt

Reputation: 75307

If you want to do it like that, you should use insertBefore();

$("<div id='four-point-five'></div>").insertBefore("#five");

Alternately, you can swop the elements around;

$("#five").before("<div id='four-point-five'></div>");

If you are after a generic solution, you might find the :last or :last-child selector interesting (depending on the rest of your HTML)

$('div:last').before("<div id='four-point-five'></div>");

Upvotes: 3

Sjoerd
Sjoerd

Reputation: 75578

It is the other way around:

$("#five").before("<div id='four-point-five'></div>");

Upvotes: 5

Related Questions