zanona
zanona

Reputation: 12717

setting default root element in jquery

jQuery currently uses window as its default element so any call like $('div') will look for div tags inside window.

Is there any way to change defaults on jQuery like:

$.defaultRoot = $('.anyOtherRootElement');
$('div').text("Hello");

this will select any div inside the elements containing .anyOtherRootElement class.

Thanks in advance


Upate

just an update refining the question a bit more here:

I would like to perform the actions above based on external queries coming from external script which won't know what defaultRoot is so they can still be calling what is supposed to be the current base, so in this instance, I'm afraid adding the a second parameter wouldn't be an option, unfortunately.

And at the same time creating a function which returns defaultRoot.find(el) would prevent me of using first-level methods such $.trim, $.each, etc… so unfortunately that would not be possible as well.

Upvotes: 3

Views: 1966

Answers (4)

Anoop
Anoop

Reputation: 23208

I don't think jQuery provide such method or variable. But you can pass second parameter in jQuery method to set context.

$.defaultRoot = $('.anyOtherRootElement');
$('div', $.defaultRoot ).text("Hello"); // all div inside $('.anyOtherRootElement')
$('div' ).text("Hello"); //all div inside body tag

Upvotes: 0

Matt Whipple
Matt Whipple

Reputation: 7134

Ideally (for performance reasons) you'd want to use find()

$.defaultRoot.find("div");

Otherwise you can use the 2 argument form that sets a context

   $("div", $.defaultRoot);

In general you don't want to do these types of things implicitly since someone else could easily end up thoroughly confused when having to work with your code later. If you want to do it consistently and make it shorter you should create your own function to do so like:

var $s = function(selector) {
  return $.defaultRoot.find(selector);
}

and then you'd just be able to use

$s("div")

or you could also do a scoped higher order function with something like

var withScope = function(scope$) {
  return function(selector) {
    return scope$.find(selector);
  }
}

var $s = withScope($.defaultRoot);
$s("div")

If for some reason you really want to screw around with the default state for client code (begging for chaos IMO), you should look at the functional practice: currying.

Upvotes: 3

Henrik Mühe
Henrik Mühe

Reputation: 429

Given that you can pass the context as a second argument, you can easily overwrite the $() operator in Javascript with a version which internally calls JQuery using jQuery.noConflict(); and always passes your new root as the second argument.

Upvotes: 0

Riz
Riz

Reputation: 10246

$('SELECTOR', 'CONTEXT')

You can use context. As in your case $('div', '.anyOtherRootElement')

For more details, visit http://api.jquery.com/jQuery/

Upvotes: 0

Related Questions