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
This is true even if the object was created with the same selector or contain references to the exact same DOM elements. // Creating two jQuery objects for the same element. Although logo1 and logo2 are created in the same way (and wrap the same DOM element), they are not the same object. For example: // Comparing jQuery objects.
Given a jQuery object that represents a set of DOM elements, the.has () method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against the descendants of the matching elements; the element will be included in the result if any of its descendant elements matches the selector.
// Comparing jQuery objects. However, both objects contain the same DOM element. The .get () method is useful for testing if two jQuery objects have the same DOM element. // Comparing DOM elements. Many developers prefix a $ to the name of variables that contain jQuery objects in order to help differentiate.
If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object. var myDomElement = document.getElementById ( "foo" ); // A plain DOM element.
What I've come up with is:
var $target = obj.find("#target").add(obj.filter("#target"));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With