Best method for selecting an object from another unknown jQuery object

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

+8
performance jquery cross-browser jquery-selectors jquery-traversing
source share
5 answers

Links to the fastest:

 var $target = obj.find('#target').addBack('#target') 
+2
source share

What I came up with:

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

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

+4
source share

You can wrap to collect another element and use the find method:

 obj.wrap('<div/>').parent().find('selector'); 

If you are worried about performance, you should not use jQuery in the first place. Vanilla JavaScript is always faster than jQuery.

An alternative is the querySelector or querySelectorAll :

 function find(html, selector) { var temp = document.createElement('div'); temp.innerHTML = html; return [].slice.call(temp.querySelectorAll(selector)); }; 
+2
source share

You can start with a new <div/> and add obj to it, and then search:

 $( '<div/>' ).append( obj ).find( '#target' ); 

Of the three, this is the second fastest.

0
source share

I would go on a search for wrap> find, because it is the most readable one (and I doubt you need to further optimize performance). But in terms of performance, you should only use the methods that you need until you need it:

 var getTarget = function(b){ for(i=0; i<b.length; i++){ if(b[i].id === 'target'){ return $(b[i]); } else { var $target = b.find('#target'); if($target.length > 0){ return $target } } } } var $target = getTartget( obj ); 

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

0
source share

All Articles