This may sound odd, but I'm working on a plugin that needs to find elements within a div, or the div itself.
The script finds an element based on a user selection, but the contents, including the markup is variable. So the script will look for the element as follows:
$('.block').find(selector); // selector set by user
but there isn't an easy way to have the selector select the '.block'. Selecting the parent before using find isn't a solution, as there are multiple '.block' elements.
I know extending the expr[":"]
selector won't work as it is only looking for children. But, I did figure out a way to "duck punch" this method, by making a ':self' selector:
(function($){
var orig = $.fn.find;
$.fn.find = function(sel){
return (sel === ':self') ? this : orig.call(this,sel);
}
})(jQuery)
But this seems a bit over the top. And it will slow jQuery processing a tiny bit with every find function. Is there another way to do this?
Thanks for the answers! But I ended up doing this:
var b = $('.block'),
el = (b.is(selector)) ? b : b.find(selector);
jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
add() Adds elements to the set of matched elements. addBack() Adds the previous set of elements to the current set. andSelf()
jQuery closest() Method An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
approach with find('*') would be much more CPU intensive and I would recommend:
$('.block').find(selector).add($('.block').filter(selector));
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