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

Advertise here 50% Off

Comment