Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force jQuery to search only in a subtree of a specified element

Is it possible to somehow reconfigure jQuery to search only in a subtree of a specified element?

I need to do something like this:

var lockToSubtree = function (jq) {
        //reconfigure jq
        return reconfiguredJQuery;
    },

    myJQuery = lockToSubtree(jQuery, '.my-namespace');

So I have my own instance of jQuery which searches elements only inside '.my-namespace'.

To illustrate my needs here is a sample HTML:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
    <div id="divOne" class="someClass"></div>
    <div class="my-namespace">
        <div id="divTwo" class="someClass"></div>
    </div>
</body>
</html>

So I can later use in my code:

var $el = myJQuery('.someClass');

And it will search .someClass only in a subtree of a .my-namespace. So it will return only div#divTwo and div#divOne will be skipped because it is not located under a subtree of .my-namespace.

The point is, that I need it to keep searching in a subtree of .my-namespace also when using jQuery functions like .closest() etc., see the final code snippet:

var $myJQuery = lockToSubtree(jQuery, '.my-namespace'),
    $el = myJQuery('.someClass'); // $el is the #divTwo element

$el.closest('body'); // finds nothing, because body is not located under .my-namespace

UPDATE:

I agree with @Keith that it is probably not possible to reconfigure jQuery to search in some subtree also with .closest method, which searches upwards. Thus I will be OK with searching in a subtree only when the search direction is down.

I would like to emphasize that I need the jQuery function to have the same functionality like original jQuery (properties like jQuery.fn etc.).

The real life scenario: I need to scope some third party library in our project so it would not affect HTML until some level of depth. The library is a one line of a JavaScript minified code using global jQuery object. All I need is to wrap it in self-invoking function and pass to it some modification of jQuery function which searches only in some subtree of a DOM, but contains all the properties as normal jQuery.

This code maybe explains it better:

(function (jQuery) {
    // I am passing jQuery through parameter
    // ... here is the library code
}(/* here I want to inject modified jQuery */));
like image 611
Roman Mazur Avatar asked Jan 11 '23 04:01

Roman Mazur


1 Answers

You can create a wrapper function for the jQuery selector like so:

$Q = function (select, opts) {
    return $(".my-namespace", opts).find(select);
};

And then just call your wrapper as you would jQuery $Q(".element").children() etc....

jSFiddle here

You can do this with closest to pass a context:

var namespace = $(".my-namespace").get()[0];

$(".foo").closest("p.bar", namespace);
like image 88
Dormouse Avatar answered Feb 02 '23 16:02

Dormouse