Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find self

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);
like image 841
Mottie Avatar asked Mar 15 '11 13:03

Mottie


People also ask

What is find () in jQuery?

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.

How do I find a specific parent in jQuery?

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.

What is addBack in jQuery?

add() Adds elements to the set of matched elements. addBack() Adds the previous set of elements to the current set. andSelf()

What is closest tr in jQuery?

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.


1 Answers

approach with find('*') would be much more CPU intensive and I would recommend:

$('.block').find(selector).add($('.block').filter(selector));
like image 194
Romans Malinovskis Avatar answered Oct 19 '22 02:10

Romans Malinovskis