Reputation: 627
<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
Reputation: 194
use this
> $("#five").before( " <div id='four-point-five'> </div> " );
Upvotes: 2
Reputation: 535
Please try this:
$("#five").before("<div id='four-point-five'></div>");
Upvotes: 1
Reputation: 11552
Try this: http://jsfiddle.net/gNQwR/
$("<div>").attr('id', 'four-point-five').text('test 4.5').insertBefore("#five");
Upvotes: 0
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
Reputation: 19217
Try this:
$("<div id='four-point-five'></div>").insertAfter("#four");
Upvotes: 2
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
Reputation: 75578
It is the other way around:
$("#five").before("<div id='four-point-five'></div>");
Upvotes: 5