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:
$obj.find('#target').andSelf().filter('#target');
? – Lamellicorn