Multiple objects in jquery selector

Posted on

Question :

As a matter of organization and performance, I often use multiple selectors together to perform a jquery method. For example:

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

This example works because the selector is a string.

However when using objects I do not know how to do 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.

Then I would like to know if there is any way to merge these objects by a comma or somehow that they are in the same selector.

Test Fiddle: link


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");



jQuery does not allow adding 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");

When doing bola[0] you are accessing the DOM element div#bola

JSFiddle 2


To do this use the method .merge() 1

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

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

I’m adding the comment code I put:

To use with two or more ID’s:

<div id="bola">bola</div>
<div id="casa">casa</div>
<div id="rodape">rodape</div>
<div id="aa">rodape</div>

JS :

$([bola, casa, rodape, aa]).css("background-color", "blue");

That way you do not have to declare the ids in vars and your code gets cleaner.


Leave a Reply

Your email address will not be published. Required fields are marked *