Reputation: 4984
Is it possible to limited the results returned in jQuery
<body>
<div id="box">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
</ul>
</div>
<script>
$(function(){
var num = 4;
console.log( $('#box').children(':first').children(num).text() );
})
</script>
</body>
This will output:
OneTwoThreeFourFiveSix
But I want:
OneTwoThreeFour
Demo Fiddle: http://jsfiddle.net/JLqrc/
Upvotes: 3
Views: 607
Reputation: 15393
$(function(){
var num = 4;
console.log($("#box ul li:lt("+num+")" ).text());
})
Upvotes: 0
Reputation: 4173
You could use .slice
too,
$('#box ul li').slice(0,4).text();
This gives you more control over what 4 elements are returned - as you can change it to .slice(1,4)
and it'll return TwoThreeFourFive etc
Here's an example: JSFiddle
Upvotes: 2
Reputation: 32581
You can use :lt()
$('#box').children(':first').children(':lt('+num+')');
or as MackieeE commented to shorten the code
$('#box li:lt('+ num +')').text()
Documentation : http://api.jquery.com/lt-selector/
Upvotes: 6