JonsonT February 2016

How I can limit number child of div jquery or javascript?

How I can limit display number (ex: 6) child of div jquery or javascript or other method?

<div class="parent">
<!--START-->
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<!--END-->
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
</div>

Answers


Dustin Poissant February 2016

What you want is the .slice method.

var divs = $(".parent .child").slice(0, 6);

console.log(divs.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<!--START-->
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<!--END-->
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
</div>


Nick Zuber February 2016

Working Fiddle

It can be done as simply using slice at the point where you want to cut off the elements, and then calling the jquery remove function:

$('.parent .child').slice(0, 6).remove();

Post Status

Asked in February 2016
Viewed 3,043 times
Voted 7
Answered 2 times

Search




Leave an answer