Best method to select an object from another unknown jQuery object

Posted by Yosi on Stack Overflow See other posts from Stack Overflow or by Yosi
Published on 2014-05-25T11:53:36Z Indexed on 2014/05/29 3:27 UTC
Read the original article Hit count: 239

Lets say I have a jQuery object/collection stored in a variable named obj, which should contain a DOM element with an id named target.

I don't know in advance if target will be a child in obj, i.e.:

obj = $('<div id="parent"><div id="target"></div></div>');

or if obj equals target, i.e.:

obj = $('<div id="target"></div>');

or if target is a top-level element inside obj, i.e.:

obj = $('<div id="target"/><span id="other"/>');

I need a way to select target from obj, but I don't know in advance when to use .find and when to use .filter.

What would be the fastest and/or most concise method of extracting target from obj?

What I've come up with is:

var $target = obj.find("#target").add(obj.filter("#target"));

UPDATE I'm adding solutions to a JSPERF test page to see which one is the best. Currently my solution is still the fastest. Here is the link, please run the tests so that we'll have more data:

http://jsperf.com/jquery-selecting-objects

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about Performance