Selecting multiple classes with jQuery

JavascriptJqueryJquery Selectors

Javascript Problem Overview


I’ve had a good look and can’t seem to find out how to select all elements matching certain classes in one jQuery selector statement such as this:

$('.myClass', '.myOtherClass').removeClass('theclass');

Any ideas on how to achieve this? The only other option is to do

$('.myClass').removeClass('theclass');
$('.myOtherClass').removeClass('theclass');

But I’m doing this with quite a few classes, so it requires much code.

Javascript Solutions


Solution 1 - Javascript

This should work:

$('.myClass, .myOtherClass').removeClass('theclass');

You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.

It's the same as you would do in CSS.

Solution 2 - Javascript

Have you tried this?

$('.myClass, .myOtherClass').removeClass('theclass');

Solution 3 - Javascript

I use $('.myClass.myOtherClass').removeClass('theclass');

Solution 4 - Javascript

// Due to this Code ): Syntax problem.    
$('.myClass', '.myOtherClass').removeClass('theclass'); 

According to jQuery documentation: https://api.jquery.com/multiple-selector/

When can select multiple classes in this way:

jQuery(“selector1, selector2, selectorN”) // double Commas. // IS valid.
jQuery('selector1, selector2, selectorN') // single Commas. // Is valid.

by enclosing all the selectors in a single '...' ' or double commas, "..."

So in your case the correct way to call multiple classes is:

$('.myClass', '.myOtherClass').removeClass('theclass'); // your Code // Invalid.
$('.myClass , .myOtherClass').removeClass('theclass');  // Correct Code // Is valid.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKezzerView Question on Stackoverflow
Solution 1 - JavascriptErik BakkerView Answer on Stackoverflow
Solution 2 - JavascriptIonuț G. StanView Answer on Stackoverflow
Solution 3 - JavascriptAdmanView Answer on Stackoverflow
Solution 4 - JavascriptRehan ShahView Answer on Stackoverflow