skip to Main Content

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.

2

Answers


  1. Have a look at add():

    $("#thing1, #thing2").add(this).toggleClass('myClass');
    
    Login or Signup to reply.
  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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search