jQuery

Get First X Number Of Elements With jQuery

Here is a quick snippet for getting the first lot of elements from a jQuery object.

Lets say you want to get the first 5 paragraphs on a page then you will start off by getting all the paragraphs on the page.

var paragraphs = $('p');

Then you use the slice() method to return the first couple of elements.

function returnElements( $obj, $value ){
     return $obj.slice(0, $value);
}

var firstFiveParagraphs = returnElements( $('p'), 5 );
Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial