Subpar Web Dev Subpar Web Dev - 6 months ago 13
Javascript Question

How to get the k-th element in a jQuery set ... AS A JQUERY ELEMENT

So I encounter this situation often and I want to figure out a better way of going about it. I using the naming convention prefixing my jQuery elements with

so that I can distinguish them from DOM elements. For example, the following:

$pointers = $('#pointer-box div.pointer');

The problem with that is, if I want to get the 3rd in the result as a jQuery, I have to do


which looks awkward. Unless there's a better way of doing this?


You can use .eq() jQuery method

$pointers = $('#pointer-box div.pointer');

var element=$pointers.eq(2);

Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.