Question

Select Elements with Multiple Classes in jQuery

csshtmljqueryjquery-selectorshtmlelements

Question

How can I use jQuery to select every element that has both the a and b classes?

For example:

<element class="a b"></element>

Using this selector returns elements with either class:

$(".a, .b")

How can I select only the intersection: elements that contain both classes?

Short Answer

You will learn how jQuery uses CSS selectors to match elements with multiple classes. In particular, you will see why .a, .b means “either class” and why .a.b means “both classes.”

Concept

jQuery accepts standard CSS selectors. To match an element that has several classes, write the class selectors together with no spaces and no comma.

$(".a.b")

This is a compound class selector. It matches an element only when both conditions are true:

  • The element has class a.
  • The same element has class b.

The order does not matter:

$(".a.b")
$(".b.a")

Both selectors match the same elements.

This matters because class attributes often represent several independent properties. For example, a button might be both button and disabled, or a notification might be both message and error. Compound selectors let you target the precise combination you need.

Mental Model

Think of each class as a requirement sticker on an item.

  • .a, .b means: select items with an A sticker or a B sticker.
  • .a.b means: select items with both an A sticker and a B sticker.
  • .a .b means: select a B-sticker item that is inside an A-sticker item.

The punctuation changes the question you ask of the page.

Take Quiz

Syntax and Examples

Use adjacent class selectors to require multiple classes on one element:

$(".firstClass.secondClass")

For the classes a and b:

<div class="a b">Matched</div>
<div class="a">Not matched</div>
<div class="b">Not matched</div>
<div class="a b c">Also matched</div>
const matchingElements = $(".a.b");

console.log(matchingElements.length); // 2

An element may have additional classes. It still matches as long as it contains every class required by the selector.

You can also include an element type when you want to narrow the match:

$("button.a.b");

That selects only <button> elements that have both a and b classes.

Step by Step Execution

Consider this HTML:

<div class="a b" id="first">First</div>
<div class="a" id="second">Second</div>
<div class="b" id="third">Third</div>
<div class="a b featured" id="fourth">Fourth</div>

And this jQuery code:

const elements = $(".a.b");
elements.addClass("selected");

Execution:

  1. jQuery reads the selector .a.b.
  2. It checks each element for class a and class b.
  3. #first has both classes, so it matches.
  4. #second has only a, so it does not match.
  5. #third has only b, so it does not match.
  6. #fourth has a, b, and featured, so it matches.
  7. addClass("selected") runs on #first and #fourth only.

The resulting matching elements have classes such as:

<div class="a b selected" id="first">First</div>

Real World Use Cases

Compound class selectors are useful whenever classes describe multiple states or roles.

  • Form validation: select fields that are required and invalid.

    $("input.required.invalid").focus();
    
  • Notifications: dismiss only error messages that are currently visible.

    $(".alert.error.visible").remove();
    
  • Interactive controls: find buttons that are disabled within a component state.

    $(".checkout-button.disabled").prop("disabled", true);
    
  • Data tables: select rows that are selected and editable.

    $("tr.selected.editable").addClass("highlight");
    
  • UI themes: apply behavior only to cards with a category and status.

    $(".product.sale.featured").append("<span>Recommended</span>");
    
Take Quiz

Real Codebase Usage

In real projects, classes often represent UI state. Developers combine them to avoid selecting unrelated elements.

Scope selectors to a component

Avoid a broad document-wide selector when the behavior belongs to one area:

const $dialog = $("#settings-dialog");
$dialog.find(".field.required.invalid").first().focus();

Use state classes deliberately

A common pattern is to add and remove a state class, then select the combination later:

$(".task").on("click", function () {
  $(this).toggleClass("completed");
});

const completedImportantTasks = $(".task.completed.important");

Prefer semantic data for business data

Classes are appropriate for presentation and UI state. If you are selecting by an identifier or a business value, a data-* attribute is often clearer:

<button class="action-button" data-status="pending">Approve</button>
$(".action-button[data-status='pending']");

Combine selection with guard clauses

Check whether there is a match before performing work that requires an element:

const $invalidFields = $(".form-field.required.invalid");

if ($invalidFields.length === 0) {
  return;
}

$invalidFields.first().focus();

Common Mistakes

Using a comma for an intersection

A comma creates a selector list, which works like OR:

// Matches elements with class a OR class b.
$(".a, .b");

Use adjacent selectors for AND:

$(".a.b");

Adding a space by accident

A space is a descendant selector, not a multiple-class selector:

// Matches an element with class b inside an element with class a.
$(".a .b");

To require both classes on the same element:

$(".a.b");

Searching for the exact class attribute text

This is fragile:

// Avoid: breaks if class order changes or another class is added.
$("[class='a b']");

It fails for class="b a" and class="a b c". Use .a.b, which is independent of class order and permits extra classes.

Forgetting the dot before each class

// Incorrect: b is interpreted as an element name.
$(".ab");

A selector for two classes needs two dots:

$(".a.b");

Expecting an exact class set

.a.b matches elements that have at least a and b; it does not require those to be the only classes. This is usually desirable.

Comparisons

SelectorMeaningExample match
.a.bSame element has a and b<div class="a b">
.a, .bElement has a or b<div class="a"> or <div class="b">
.a .bA .b element is inside an .a element<div class="a"><span class="b"></span></div>
div.a.bA div has both classes<div class="a b">
[class~="a"][class~="b"]Same element has both class tokens<div class="a b">

The attribute-selector form is valid but more verbose. Prefer .a.b for class matching.

Take Quiz

Cheat Sheet

// Both classes on the same element
$(".a.b");

// Either class
$(".a, .b");

// Class b inside an element with class a
$(".a .b");

// A specific element type with both classes
$("button.a.b");

// Find matching elements inside one container
$("#container").find(".a.b");

Rules:

  • Put a . before every class name.
  • Do not put a space between classes when they belong to the same element.
  • Do not use commas when all classes are required.
  • Class order does not matter: .a.b and .b.a are equivalent.
  • Extra classes do not prevent a match.

FAQ

How do I select an element with two classes in jQuery?

Use adjacent class selectors with no spaces:

$(".a.b")

Does .a.b require the classes to appear in that order in HTML?

No. Both class="a b" and class="b a" match .a.b.

Does .a.b match an element with extra classes?

Yes. An element with class="a b c" matches because it contains both required classes.

What is the difference between .a.b and .a .b?

.a.b requires both classes on one element. .a .b selects a .b descendant inside an .a element.

Why does $(".a, .b") return too many elements?

The comma means “match either selector.” It selects elements with a, elements with b, and elements with both.

Can I use this with event handlers?

Yes. For example:

$(document).on("click", ".button.primary", function () {
  console.log("A primary button was clicked.");
});

Is .a.b jQuery-specific?

No. It is a standard CSS selector. It also works with document.querySelectorAll(".a.b") in modern browsers.

Take Quiz

Mini Project

Description

Build a small task list filter that highlights tasks which are both marked as urgent and still open. This demonstrates how multiple classes can describe separate UI states and how .urgent.open targets their intersection.

Goal

Highlight only task items that have both the urgent and open classes.

Requirements

Create at least four task list items with different class combinations. Use urgent and open as independent state classes. Add a button that highlights only tasks with both classes. Show how many urgent open tasks were found. Do not highlight tasks that have only one of the two classes.

Take Quiz

Keep learning

Related questions

View more