28

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.

2
  • 2
    BTW: A number as first character for ID-declaration is never a good idea... ;-) Commented Jan 31, 2013 at 16:40
  • 2
    @yckart They are never named that way. This is for the purpose of illustration only. Commented Jan 31, 2013 at 16:57

3 Answers 3

38

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

$([one, two, three, four]).each(function() {
    // your function here
});
Sign up to request clarification or add additional context in comments.

Comments

11

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.

1 Comment

This is nice, you might get even more benefit from the approach by using it like: groupOne.click(function(e){});
5

You could put them into an array like this

var k = [one,two,three,four]

$.each(k,function(){
  $(this).click(function(){
     //Function here
   });
});

1 Comment

Or just do this: $(k).click(function(){...})

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.