4

How can I add an item before the siblings?

For instance,

<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>

So I want to add this item before of them.

<div class="item">0</div>

This one does not work of course!

$('<div class="item">0</div>').insertBefore(".item").siblings(); 

This is what I need in the result,

<div class="item">0</div>
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
Run
  • 54,938
  • 169
  • 450
  • 748

4 Answers4

5

This should work:

$('<div class="item">0</div>').insertBefore(".item:first");

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
3

Select the first .item and insert your new element before it:

$(".item:first").before("<div class='item'>0</div>");

Here's a working example.

Alternatively (for better performance), use filter:

$(".item").filter(":first").before("<div class='item'>0</div>");
James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

Try this one:

$('.item:eq(1)').parent().prepend('<div class="item">0</div>')
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
0

how about:

$("div.class:first").before("<div class='item'>0</div>");
kaveman
  • 4,339
  • 25
  • 44