jquery apply listener to set of elements [duplicate]

I'm trying to figure out if there is a solution to this simple but complex task.

Let's say we have this variables:

var dom1 = $('.selector1');
var dom2 = $('.selector2');

Now I want to apply for example a listener to dom1 and dom2. Is there a different, direct and more reliable solution than apply one by one the function?

dom1.click(function(){
    //a lot of stuff
}
dom2.click(function(){
    //the same lot of stuff
}
//or
$([dom1,dom2]).each(function(){
    this.click(function(){
        //the same lot of stuff
    });
}

I know this is not a working solution, but I'm searching something like this:

//NOT WORKING, NON-SENSE, I KNOW
$([dom1,dom2]).click(function(){
    //the same lot of stuff
}

thank you in advance.

Answers:

Answer

You can either select both sets elements using a comma separated selector:

$('.selector1, .selector2').click(fn);

Alternatively, you can use add() to join together two variables which contain jQuery objects:

dom1.add(dom2).click(fn);
Answer

You can use jQuery.add which adds the element to the current collection.

dom1.add(dom2).click(function(){
    // your code goes here
});

Else, you can use selectors separated by a comma.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.