lucasgabmoreno
lucasgabmoreno

Reputation: 1031

jQuery - Join jQuery Objects, equivalent to Multiple Selector

I have this:

$(window).load(function(){
   var var1 = $('selector1').find('iframe').contents().find('body').find('selector2')
   var var2 = $('selector3');
   // Some function
   }); //end

I can do this: (somefunction() doesn't exists as a function, it could be any function)

$(var1).somefunction(someattributes);
$(var2).somefunction(someattributes);

But I want to do something like this: (jointhisselectorwith() doesn't exists as a function, it's what I want)

$(var1).jointhisselectorwith(var2).somefunction(someattributes);

It's possible to join jQuery objects? Thanks!

Upvotes: 1

Views: 119

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075865

You can use add.

If var1 and var2 contain selectors:

$(var1).add(var2).somefunction(someattributes);

Or it also works with jQuery instances (which is what you have, you didn't need the $(var1) bit at all):

var j1 = $(var1);
var j2 = $(var2);
j1.add(j2).somefunction(someattributes);

Gratuitous live example:

setTimeout(function() {
  var var1 = ".foo";
  var var2 = ".bar";
  $(var1).add(var2).css("color", "green");
  setTimeout(function() {
    var j1 = $(".foo");
    var j2 = $(".bar");
    j1.add(j2).css("color", "blue");
  }, 500);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div class="foo">I'm foo</div>
<div class="bar">I'm bar</div>
<div class="foo">I'm foo</div>
<div class="bar">I'm bar</div>
<div class="foo">I'm foo</div>
<div class="bar">I'm bar</div>

Upvotes: 3

Related Questions