0

I have this:

var $e1 = $('#e1');
var $e2 = $('#e2');
var $e3 = $('#e3');

This doesn't work:

var $all = [$e1, $e2, $e3];
$($all).css('background', '#ff0000');

How should I do this, while reusing $el1, $el2, $el3?

I don't want to do:

$('#e1, #e2, #e3')

This is probably very simple to do, but I don't know what to search for to find out.

5
  • 1
    Why don't you want to do $('#e1, #e2, #e3') if I may ask ? Commented Jan 21, 2011 at 14:07
  • The $-prefix in variable names is for jQuery objects. Don't use it for regular arrays, it will only confuse you. Commented Jan 21, 2011 at 14:27
  • @Šime Vidas: Can you explain a little better when I should and shouldn't start a variable with $ according to "jQuery style". Commented Jan 21, 2011 at 14:42
  • This is an array: [1, 2, 3]. This is a jQuery object: $('div'). When choosing a variable name, you use the $-prefix for those variables which values are jQuery objects. For instance: var x = true; var y = [1,2,3]; var $z = $('#z'); Commented Jan 21, 2011 at 14:52
  • @Šime Vidas: Thanks, I will try to do this from now on. Commented Jan 21, 2011 at 15:23

7 Answers 7

3

You can do this:

var $all = $e1.add($e2).add($e3);

Or this (looks a little obtuse, but it's the correct way - you have to extract the node from the jQuery object first with [0]):

var $all = $([$e1[0], $e2[0], $e3[0]]);

Note: in my examples, $all is already a jQuery object, so you don't need to wrap it again like this: $($all). Just do:

$all.css('background', '#ff0000');
Sign up to request clarification or add additional context in comments.

1 Comment

[0] is what I was really looking for. Thanks for the explanation.
0

Edit: even better:

var $e1 = $('#e1');
var $e2 = $('#e2');
var $e3 = $('#e3');
var all = $e1.add($e2).add($e3);
all.css('background', '#ff0000');

Comments

0
$e1.add($e2).add($e3)

is another way of merging different elements/jQuery objects.

Reference: .add()

Comments

0

Edit: wrap array in jQuery instance and iterate through its elements

all = [$e1, $e2, $e3];

$(all).each(function(index, element){
   element.css('background', '#ff0000');
})

Comments

0

Well if you don't want to use a selector, apply the style to each element of the array.

for(i = 0; i < $all.length; i++)
    $all[i].css('background', '#ff0000');

Comments

0

you can do what you have in your example:

var $all = [$e1, $e2, $e3],
    i = $all.length;

for(; i--;) {
    $all[i].css('background', '#f00');
}

Comments

0

It seems you ca do just this:

$(deleteBtn).add(copyBtn).add(moveBtn).css('background', 'white');

As it says here http://api.jquery.com/add/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.