What I'm trying should be easy, but I don't seem to be able to figure it out (ore google the problem)
I have elements that I find, after finding them I want to append them to a container. But I don't want to many items so I want to be able to limit the amount of items to be appended.
For example:
<div class="appending">
</div>
<div class="toAppend">
<div class="box project">
<h3>Project Box</h3>
</div>
<div class="box project">
<h3>Project Box</h3>
</div>
<div class="box social">
<h3>Social Box</h3>
</div>
<div class="box video">
<h3>Video Box</h3>
</div>
<div class="box project">
<h3>Project Box</h3>
</div>
<div class="box social">
<h3>Social Box</h3>
</div>
</div>
Here are 3 items in div.toAppend that I would like to append to the div.appending
var appenditems = $(".toAppend").find(".project");
appenditems.appendTo(".appending");
This is easy, but my problem is that I want to limit the amount of div.project that are appended , for example, only append the first 2 that I find. I'm unsure of any way to do this.
What I'm trying should be easy, but I don't seem to be able to figure it out (ore google the problem)
I have elements that I find, after finding them I want to append them to a container. But I don't want to many items so I want to be able to limit the amount of items to be appended.
For example:
<div class="appending">
</div>
<div class="toAppend">
<div class="box project">
<h3>Project Box</h3>
</div>
<div class="box project">
<h3>Project Box</h3>
</div>
<div class="box social">
<h3>Social Box</h3>
</div>
<div class="box video">
<h3>Video Box</h3>
</div>
<div class="box project">
<h3>Project Box</h3>
</div>
<div class="box social">
<h3>Social Box</h3>
</div>
</div>
Here are 3 items in div.toAppend that I would like to append to the div.appending
var appenditems = $(".toAppend").find(".project");
appenditems.appendTo(".appending");
This is easy, but my problem is that I want to limit the amount of div.project that are appended , for example, only append the first 2 that I find. I'm unsure of any way to do this.
Share Improve this question edited Nov 22, 2011 at 15:38 Kris van der Mast 16.6k8 gold badges40 silver badges64 bronze badges asked Nov 22, 2011 at 15:36 Einar ÓlafssonEinar Ólafsson 3,1971 gold badge20 silver badges28 bronze badges5 Answers
Reset to default 3...for example, only append the first 2 that I find.
appenditems.slice(0,2).appendTo(".appending");
You can use the :lt
selector:
var appenditems = $(".toAppend").find(".project:lt(2)");
appenditems.appendTo(".appending");
jQuery's Slice
var LIMIT = 2;
var appenditems = $(".toAppend").find(".project");
appenditems.slice(0, LIMIT).appendTo(".appending");
Example
Try using :lt selector which select all elements at an index less than index within the matched set.
$(".toAppend").find(".project:lt(2)").appendTo(".appending");
$('.toAppend .project:lt(2)').appendTo('.appending');