views:

70

answers:

3

For example I have a function that has one argument, it can be DOM element ID or className. How can I select only first element wrapped with jQuery?

$(value).get(0) and $(value)[0] returns just the plain DOM element, not a jQuery wrapped element.

+3  A: 
$(value).eq(0);
// or
$(value).first();
// or
$(value + ':eq(0)');
// or
$(value + ':first');
jigfox
The method forms like `first()` are always to be preferred over the selector versions like `:first`. These are non-standard selectors, which will force jQuery to use the relatively slow Sizzle library to do selector matching instead of the browser's fast native `querySelectorAll()`.
bobince
+4  A: 
$(value).first();

See http://api.jquery.com/first/

Given a jQuery object that represents a set of DOM elements, the .first() method constructs a new jQuery object from the first matching element.

jensgram
There are plenty of ways (cf. the other answers). You can even wrap the result from `$(value)[0]` or `$(value).get(0)` again, e.g., `$($(value)[0])` :)
jensgram
+1, this is about ten times faster than using `:first`, according to some dude called 'moltendorf' who posted a benchmark in the comments section of the documentation: http://api.jquery.com/first/#comment-37524554
karim79
@karim79 - the faster version would be `.eq(0)` though, since it's an alias :) @jensgram - pleeeeeeease don't do that, it's tremendously wasteful and less flexible :)
Nick Craver
@Nick Craver I assume you're referring to the horrible `$($(value)[0])`. The smiley was meant to emphasize that this was even *another* way ... a way to avoid, though. @Roman *Don't!*
jensgram
+2  A: 

You can use :first (if it's a selector), like this:

$(value:first)

Or .eq(0) like this:

$(value).eq(0)

Or .first() (just an alias for .eq(0)) like this:

$(value).first()
Nick Craver