Multiple objects in jquery selector

Question:

For reasons of organization and performance I usually use several selectors together to perform a jquery method. For example:

$("#bola, #casa, #arvore").css("background-color", "blue");

In this example it works because the selector is a string.

But when using objects I don't know how to make this join.

New scenario:

var bola = $("#bola");
var casa = $("#casa");
var arvore = $("#arvore");

$(bola, casa, arvore).css("background-color", "blue");

In this case only the "ball" background is painted.

Or concatenating with a comma:

$(bola+ ","+ casa + "," + arvore).css("background-color", "blue");

In this case, neither is painted, as expected.

So I would like to know if there is any way to join these objects by comma or somehow that they stay in the same selector.

Test fiddle: http://jsfiddle.net/nsMw3/

NOTE: It is not worth putting var items = $("#ball, #home"), because I use objects that are brought in a much more complex way, and define them one by one.

Answer:

You can use the add() method to combine objects into a set

var bola = $("#bola");
var casa = $("#casa");

$(bola).add(casa).css("background-color", "blue");

JSFiddle

Option

jQuery doesn't allow you to add multiple elements at once to a jQuery object, one option would be to add multiple pure DOM elements to an array:

var bola = $('#bola'),
    casa = $('#casa'),
    arvore = $('#arvore');

// array de elementos DOM 
$( [bola[0], casa[0], arvore[0]] ).css("background-color", "blue");

By making bola[0] you are accessing the DOM element div#bola

JSFiddle 2

Scroll to Top