Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method to select an object from another unknown jQuery object

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

like image 333
BlueYoshi Avatar asked May 25 '14 11:05

BlueYoshi


People also ask

Can two jQuery objects be created with the same selector?

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.

How do I include an element in a jQuery selector?

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.

How do you compare two jQuery objects with the same element?

// 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.

How to select elements related to a DOM element using jQuery?

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.


1 Answers

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

like image 124
BlueYoshi Avatar answered Oct 12 '22 02:10

BlueYoshi