Suppose I have a jQuery object / collection stored in a variable named obj that should contain a DOM element with an identifier named target.
I do not know in advance if the target will be a child in obj, that is:
obj = $('<div id="parent"><div id="target"></div></div>');
or if obj is equal , i.e.:
obj = $('<div id="target"></div>');
or if the target is a top-level element inside the obj object, that is:
obj = $('<div id="target"/><span id="other"/>');
I need a way to select a target from obj, but I donβt know in advance when to use .find and when to use .filter.
What will be the fastest and / or most concise way to extract a target from obj?
What I came up with:
var $target = obj.find("#target").add(obj.filter("#target"));
UPDATE I am adding solutions to the JSPERF test page to find out which one is better. At present, my solution is still the fastest. Here is the link, please run the tests so that we have more data:
http://jsperf.com/jquery-selecting-objects
performance jquery cross-browser jquery-selectors jquery-traversing
Yosi
source share