jquery: How can I add an item before the siblings?
Asked Answered
J

4

5

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>
Jellify answered 25/8, 2011 at 17:42 Comment(0)
F
4

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>");
Feldspar answered 25/8, 2011 at 17:46 Comment(0)
A
5

This should work:

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

Ashely answered 25/8, 2011 at 17:45 Comment(0)
F
4

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>");
Feldspar answered 25/8, 2011 at 17:46 Comment(0)
K
1

Try this one:

$('.item:eq(1)').parent().prepend('<div class="item">0</div>')
Kessiah answered 25/8, 2011 at 17:46 Comment(0)
B
0

how about:

$("div.class:first").before("<div class='item'>0</div>");
Bellda answered 25/8, 2011 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.