Assuming the following html structure :
<div id="anId">
<span id="1"> aSpan </span>
<span id="2"> anotherSpan </span>
</div>
<span id="3"> anOutsideSpan </span>
Is there a way to define a “global context” for jQuery selectors? Something like:
$(IDoNotKnowWhatToDoHere). SomethingAboutContext; // Defining the context as div#anID
$('span').doSomething; // Action only on span#1 and span#2 and not on span#3
$('span#1').doSomethingElse;
$('span').doSomethingStrange;
$('span#2').doSomethingCool;
$(SomethingAboutRemovingGlobalContext); //Removing the context
That way i can avoid doing this :
$('div#anId span').doSomething; // Action only on span#1 and span#2 and not on span#3
$('div#anId span').doSomethingElse; // Same as last code comment
$('div#anId span#1').doSomethingStrange; // Same as last code comment
$('div#anId span#2').doSomethingCool; // Same as last code comment
There is only 4 actions here but the code i’m working on has something like 100.
I want to avoid always repeting the div#anId.
-
Keep in mind it’s an example, not actual code.
-
My question is not about chaining.
So what your doing here is your creating a new selector that delegates to
$("div").findand using that for all your selecting.