Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple jQuery objects with .add()

Does the .add() method allow selecting multiple objects in one go instead of adding one at a time?

one.add(two).add(three).add(four).on("click", function() { }); 

The following variables are set in the way they do because each carries a different function.

var one   = $("#1"); var two   = $("#2"); var three = $("#3"); var four  = $("#4"); 

But what if I want to add an extra function that applies to all of these elements? Do I have to add them one by one?

I know you can select them all using $("#1,#2,#3,#4"), but I just want to make use of the above variables.

like image 312
Antony Avatar asked Jan 31 '13 13:01

Antony


People also ask

Can you select multiple elements in jQuery?

In jQuery, you can select multiple elements by separate it with a comma “,” symbol.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


2 Answers

I'd prefer this array approach, purely for readability...

$([one, two, three, four]).each(function() {     // your function here }); 
like image 74
Reinstate Monica Cellio Avatar answered Sep 17 '22 09:09

Reinstate Monica Cellio


You cannot add multiple objects in one go, for example:

var groupThree = one.add(three, five); // will not work as expected 

You could cache the added objects so that you only have to do the add one time - http://jsfiddle.net/X5432/

var one   = $("#1"); var two   = $("#2"); var three = $("#3"); var four  = $("#4"); var five  = $("#5");  var groupOne = one.add(two).add(three).add(four); var groupTwo = groupOne.add(five);  $('#first').click(function(e){     e.preventDefault();     groupOne.css({'background': '#00FF00'}); });  $('#second').click(function(e){     e.preventDefault();     groupTwo.css({'background': '#FF0000'}); }); 

But I like the array method better, this is just a different way of thinking about it.

like image 28
Jay Blanchard Avatar answered Sep 21 '22 09:09

Jay Blanchard