开发者

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

开发者 https://www.devze.com 2023-03-31 07:17 出处:网络
How can I add an item before the siblings? For in开发者_开发知识库stance, <div class=\"item\">1</div>

How can I add an item before the siblings?

For in开发者_开发知识库stance,

<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>


This should work:

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


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>");


Try this one:

$('.item:eq(1)').parent().prepend('<div class="item">0</div>')


how about:

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

精彩评论

暂无评论...
验证码 换一张
取 消