Selecting items in a jQuery cached object

Suppose we are given the following element:

var cachedElement = $('<div><p>Some text</p></div><aside>Some more text</aside>'); 

If I know what is in the element, I can easily go through it. For example, to find a div, I can use:

 cachedElement.filter('div'); 

and find the child that I can use:

 cachedElement.find('p'); 

What if I do not know the structure of the cached element. How to look for an element that can be parent, child, or both.

I was wondering if there is a way that can do this for me. I don't want to wrap an element in a div and search with .find ().

My best solution is the following inefficient (and ugly) selector:

 cachedElement.filter('selector_string').add(cachedElement.find('selector_string')).eq(0) 

In my specific case, I only need the first element.

Any ideas? Thanks

+4
source share
2 answers

You can take your original approach and add it to the plugin if you want something a little cleaner:

 (function( $ ) { $.fn.inclusiveFind = function( sel ) { return this.filter( sel ).add( this.find( sel ) ); } })( jQuery ); 

Then call it, like any other method:

 var cachedElement = $('<div><p>Some text</p></div><aside>Some more text</aside>'); var div = cachedElement.inclusiveFind( 'div' ).eq(0); var p = cachedElement.inclusiveFind( 'p' ).eq(0); 

You can improve performance using the jQuery.merge() [docs] method:

 (function( $ ) { $.fn.inclusiveFind = function( sel ) { return $.merge( this.filter( sel ), this.find( sel ) ); } })( jQuery ); 
+1
source

I see no reason why you don’t want to wrap the contents in a div :

 $('<div />').append(cachedElement).find('selector_string').eq(0); 

You can do something like:

 cachedElement.find('*').andSelf().filter('selector_string').eq(0); 

This will select all descendants of cachedElement and add cachedElement . That way, you would select all the elements in a single jQuery object. But it seems to me ineffective.

+2
source

All Articles