ttmt
ttmt

Reputation: 4984

jQuery limit the results/selection returned

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

Answers (3)

Sudharsan S
Sudharsan S

Reputation: 15393

$(function(){
      var num = 4;
    console.log($("#box ul li:lt("+num+")" ).text());

  })

Upvotes: 0

DannyTheDev
DannyTheDev

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

Anton
Anton

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

DEMO

Documentation : http://api.jquery.com/lt-selector/

Upvotes: 6

Related Questions