3

I want to combine these two statements into one.

$("#thing1, #thing2").toggleClass('myClass');
$(this).toggleClass('myClass');

Instincts told me this might work:

$("#thing1, #thing2", this).toggleClass('myClass');

but after some research, I discovered it is equivalent to this:

$(this).find("#thing1, #thing2").toggleClass('myClass');

I can't find anything in the documentation about doing this.

Pete
  • 57,112
  • 28
  • 117
  • 166
Uuuuuumm
  • 608
  • 5
  • 21

2 Answers2

4

Have a look at add():

$("#thing1, #thing2").add(this).toggleClass('myClass');
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
2

You could use $.merge

$('span').on('click', function() {
  $.merge($(this), $("#thing1, #thing2")).toggleClass('red')
});
.red {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="thing1">thing1</div>
<div id="thing2">thing2</div>
<span>click</span>
Pete
  • 57,112
  • 28
  • 117
  • 166