Take the 2-minute tour ×

I want wrote a elegant solution that select a same tag by searching in a list of different contexts

//i have this not editable code
var c1$ = $('#context1'),
    c2$ = $('#context2'),
    c3$ = $('#context3');

//I want to improve the code and 'only from here on
var selector = 'a.select';

I'm searching a solution for arbitrary number of contexts

share|improve this question
add comment

3 Answers

You can use $.add() to build up your context, and then use it as a single jQuery object within the context parameter of your selector:

var $foo = $("#foo"),
    $bar = $("#bar");

var $context = $foo.add($bar);

$("a.select", $context).css("color", "red");
share|improve this answer
@StefanoCudini Updated the answer per your comments. –  Jonathan Sampson May 1 '12 at 23:10
good idea! but my real problem is that i have the contexts selectors into a variables See my code edit above please –  StefanoCudini May 1 '12 at 23:13
@StefanoCudini See the latest update. –  Jonathan Sampson May 1 '12 at 23:34
well thanks, I was trying this solution right now and I was wondering if it can aggregate any number of contexts included in an array –  StefanoCudini May 1 '12 at 23:38
$foo.add($bar).add($fiz).add($buz). You can add as many as you like. –  Jonathan Sampson May 1 '12 at 23:42
show 4 more comments

Why don't load a list of context, and then do a foreach to find the 'a.select' in each of the context?.

share|improve this answer
i already thought about this, but I want to leave it as a final solution, now I wanted to find a most elegant solution ;-) –  StefanoCudini May 1 '12 at 23:21
add comment

my desperate not elegant solution

var contexts = [$('#context1'),$('#context2'),$('#context3')];
//list of contexts in single variable(arbitrary number!)

var selector = 'a.select';
//same selector for all variable contexts

var cons$ = $([]);
//empty temporary selector

for(i in contexts)
    cons$ = cons$.add(contexts[i]);

var allmatches$ = cons$.find(selector);

//here processing allmatches$

allmatches$.css("color", "red"); 
//now apply css in one step
share|improve this answer
add comment

Your Answer


