Assume we were passed 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 traverse it. For example, to find the div I can use:
cachedElement.filter('div');
and to find a child element I can use:
cachedElement.find('p');
What if I do not know the structure of the cached element. How can I search for an element, which can be parent, child or both.
I was wondering if there is a method that can do that for me. I do not want to wrap the element in divs 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 particular case i need only the first element.
Any ideas? Thanks
I don't see any reason why you would not want to wrap the content in a div
:
$('<div />').append(cachedElement).find('selector_string').eq(0);
You could do something like:
cachedElement.find('*').andSelf().filter('selector_string').eq(0);
This will select all descendants of cachedElement
and add cachedElement
. So you would have selected all the elements in one jQuery object. But that seems rather inefficient to me as well.
You could take your original approach, and make it into a plugin if you wanted 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 may get a performance improvement by using the jQuery.merge()
[docs] method:
(function( $ ) {
$.fn.inclusiveFind = function( sel ) {
return $.merge( this.filter( sel ), this.find( sel ) );
}
})( jQuery );
精彩评论