Selecting only one element in the jQuery collection

javascript, jquery

Solution

A `jQuery` selection returns an array. Therefore `$("selection")[0]` can work. However there are better abstracted methods for this, like `.get(0)` or `.first()` (in case you're looking for the first element of the selection/array).

$("selection").get(index) returns the pure DOM element (at that specific index) of the selection, and is not wrapped in the jQuery object.

$("selection").first() returns the first element of the selection, and wraps it in a jQuery object.

So if you don't necessarely want to return the first element, but still want jQuery functionality, you can do `$($("selection").get(index))`.

Given your situation, this should work fine:

// bind the 'onclick' event only on the first element of the selection
$( "ul>li>a" ).first().click(function() {
    $( "ul ul").prepend("<li class='close'>Close</li>");
}); 

Which is equivalent to this:

$($( "ul>li>a" ).get(0)).click(function() {
    $( "ul ul").prepend("<li class='close'>Close</li>");
});

And this:

$($( "ul>li>a" )[0]).click(function() {
    $( "ul ul").prepend("<li class='close'>Close</li>");
});

I must disagree with Ryan, working on the CSS selection string to filter the result is rather expensive compared to the native JavaScript array functionality.

Problem

How do I limit an event to a single element in a jQuery collection? In the case below, I've tried using `.one()` to limit the behaviour (inserting the `<li class='close'>Close</li>` line of HTML) to a single instance. The behaviour does indeed happen only once, but on EVERY matched element of `$( "ul>li>a" )`. How do I make it happen only once, to only ONE of the matched elements in the collection? Any ideas? ``` $( "ul>li>a" ).one( "click", function(){ $( "ul ul") .prepend("<li class='close'>Close</li>") } ); ``` Thanks in advance. -AS

Original source