We can use jQuery to select multiple classes of an HTML element by simply separating each class by a comma. Take a look at how we do this in the code below:

$(".class1, .class2, .class3")

Let’s see a quick example of this.


Let’s say I have the following HTML:

This is a paragraph.

This is a div.

This is a paragraph.

This is a div.

If we wanted to add some style to all of the divs and paragraphs in the div, #div1, we could select all of these classes and then change the styles of them all at once. Here is the jQuery code that we would need:

$(".class1, .class2, .class3, .class4").css("background","green");

The code above would change the background color of each element in #div1 to green.

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery(".class1, .class2, .class3, .class4").css("background","green");

Example of Using jQuery to Select Multiple Classes

In this example, we will let the user click a button that will change the styles of some divs and paragraphs as we did in the example above.

Here is the HTML setup:

This is a paragraph.

This is a div.

This is a paragraph.

This is a div.
Change font size

We can utilize both the jQuery click() method and jQuery css() method to add some styles to the elements in div #div1.

We can do this all at once by using jQuery to select multiple classes as we showed above.

In this example, we will simply change the font size of the elements.

Below is the JavaScript and jQuery code we need to do this:

$("#click-me").click(function(){
  $(".class1, .class2, .class3, .class4").css("font-size","24px");
});

The final code and output for this example of how to select multiple classes using jQuery and JavaScript is below:

Code Output:

This is a paragraph.

This is a div.

This is a paragraph.

This is a div.

Change font size

Full Code:

This is a paragraph.

This is a div.

This is a paragraph.

This is a div.
Change font size

Hopefully this article has been useful for you to understand how to use jQuery to select multiple classes.

Categorized in:

jQuery,

Last Update: February 26, 2024