Force jQuery to search only in the subtree of the given element

Is it possible in some way to reconfigure jQueryfor search only in the subtree of the 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 jQuery instance that searches for elements only inside '.my-namespace'.

To illustrate my needs, an HTML example is provided:

<!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>

Therefore, I can use later in my code:

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

And he will search .someClassonly in the subtree .my-namespace. Therefore, he will return only div#divTwoand div#divOnewill be skipped, because he is not under the subtree .my-namespace.

, , .my-namespace jQuery .closest() .., . :

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:

@Keith , , , jQuery .closest, . , , .

, jQuery, , jQuery ( , jQuery.fn ..).

. ​​ , HTML . - JavaScript jQuery. , , jQuery, DOM, jQuery.

, , :

(function (jQuery) {
    // I am passing jQuery through parameter
    // ... here is the library code
}(/* here I want to inject modified jQuery */));
+3
3

@Dormouse @ArunPJohny, , jQuery jQuery.fn, .

@ArunPJohny code :

(function (jQuery) {
    // third party library using my own modified jQuery function
}((function ($) {

    var $wrapper = $('.cms-bootstrap'),
        scopedjQuery = function (selector) {
            return $(selector, $wrapper);
        };

    // Copy all jQuery properties into
    // scopedjQuery so they can be used later
    for (var k in $) {
        if ($.hasOwnProperty(k)) {
            scopedjQuery[k] = $[k];
        }
    }

    return scopedjQuery;

}(window.jQuery.noConflict()))))
0

- jQuery :

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

, jQuery $Q(".element").children() etc....

jSFiddle

, :

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

$(".foo").closest("p.bar", namespace);
+6

, jQuery , .closest() DOM . - , , , - .my-namespace . .closest() , , .

.closest(), , , , Dormouse .

+3

All Articles