jQuery .addClass() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Class names

What You’ll Learn

The .addClass() method appends one or more CSS class names to each matched element — it never replaces existing classes. This tutorial covers all four API overloads (string, array, callback, callback returning array), comparisons with .removeClass(), .toggleClass(), and .css(), and practical tab-toggle patterns.

01

String

.addClass("x")

02

Multiple

Space or array

03

Callback

Per element

04

vs remove

Strip classes

05

vs css

Classes vs inline

06

Since 1.0

Core API

Introduction

Styling in modern web pages usually lives in CSS files — reusable class names like .active, .error, or .hidden that you toggle on elements at runtime. When JavaScript needs to turn a style on, jQuery provides .addClass().

Available since jQuery 1.0, .addClass() updates the class attribute on each matched element. It appends new class names without removing what is already there — unlike setting element.className directly, which would wipe existing classes. For inline property values, use .css() instead.

Understanding the .addClass() Method

Given a jQuery object representing one or more DOM elements, .addClass() adds the specified class name(s) to each element’s class attribute. Styles defined in your stylesheet for those classes take effect immediately — no need to set individual CSS properties in JavaScript.

Think of classes as labels you stick onto elements. .addClass() adds more labels; .removeClass() peels them off; .toggleClass() flips a label on or off. This keeps presentation in CSS and behavior in JavaScript — a clean separation of concerns.

💡
Beginner Tip

$("p").last().addClass("selected") adds selected to the last paragraph only — every other class on that element stays untouched.

📝 Syntax

jQuery .addClass() accepts four argument forms:

1. String — one or more class names (since 1.0)

jQuery
.addClass( className )
  • className — a string of one or more space-separated CSS class names to add to each matched element.

2. Array — list of class names (since 3.3)

jQuery
.addClass( [ classNames ] )
  • classNames — an array of strings; jQuery adds every entry to each element.

3. Function — per-element class name (since 1.4)

jQuery
.addClass( function( index, currentClass ) {
  // return className string
} )
  • index — zero-based index of the element within the matched set.
  • currentClass — the element’s current class attribute value (or empty string).
  • Return a string of class name(s) to add for that element.

4. Function returning array (since 3.3)

The callback may return an array of class names instead of a space-separated string:

jQuery
$( "li" ).addClass( function( index ) {
  return [ "item-" + index, "row-" + index ];
} );

Return value

  • The original jQuery object (for chaining) — not a new collection.

Official jQuery API example

jQuery
$( "p" ).last().addClass( "selected" );

// Last paragraph gets class "selected" — other classes preserved

⚡ Quick Reference

GoalCode
Add one class$("p").addClass("highlight")
Add multiple classes (string)$("p").addClass("selected highlight")
Add multiple classes (array, 3.3+)$("p").addClass(["selected", "highlight"])
Index-based class per element$("li").addClass(function(i){ return "item-"+i; })
Remove then add (switch state)$(".tab").removeClass("active").addClass("active")
Inline style instead$("p").css("color", "red")

📋 .addClass() vs .removeClass() vs .toggleClass() vs .css()

Four styling approaches — append classes, strip classes, flip classes, or set inline properties.

.addClass()
+ class

Append class names — keeps existing classes

.removeClass()
- class

Strip one, some, or all classes

.toggleClass()
on/off

Add if missing, remove if present

.css()
inline

Set style properties directly on the element

Examples Gallery

Examples 1–4 follow the official jQuery API documentation. Example 5 shows a practical tab toggle. Use DevTools or the Try-it links to run each snippet in the browser.

📚 Getting Started

Official jQuery demos for adding CSS classes.

Example 1 — Official Demo: Add selected to Last Paragraph

Highlight the final paragraph by appending the selected class.

jQuery
$( "p" ).last().addClass( "selected" );
Try It Yourself

How It Works

.last() narrows to one element, then .addClass() appends selected to its existing classes without touching the other paragraphs.

Example 2 — Official Demo: Add Two Classes With a String

Pass a space-separated string to add multiple classes in one call.

jQuery
$( "p" ).last().addClass( "selected highlight" );
Try It Yourself

How It Works

jQuery splits the string on spaces and adds each class name. Both stylesheet rules apply to the same element simultaneously.

Example 3 — Official Demo: Array Syntax (jQuery 3.3+)

Pass an array when you already have class names in a JavaScript array.

jQuery
$( "p" ).last().addClass( [ "selected", "highlight" ] );
Try It Yourself

How It Works

The array form (added in jQuery 3.3) avoids building a space-separated string manually — handy when class names are computed or stored in an array.

Example 4 — Official Demo: Callback With Index

Add a unique class to each list item based on its position.

jQuery
$( "ul li" ).addClass( function( index ) {
  return "item-" + index;
} );
Try It Yourself

How It Works

jQuery invokes the callback once per matched element. The returned string becomes the class name to add. Since 3.3 the callback can return an array of class names instead.

📈 Practical Patterns

Combine .removeClass() and .addClass() for exclusive state switches.

Example 5 — Tab Toggle With .removeClass() and .addClass()

Clear active from all tabs, then add it to the clicked tab — a common UI pattern.

jQuery
$( ".tabs" ).on( "click", ".tab", function() {
  $( ".tab" ).removeClass( "active" );
  $( this ).addClass( "active" );
} );
Try It Yourself

How It Works

.removeClass("active") strips the state from every tab; .addClass("active") on $(this) marks only the clicked one. You could use .toggleClass() for simple on/off, but remove-then-add guarantees exactly one active tab.

🚀 Common Use Cases

  • Active navigation item$("nav a").removeClass("active"); $(this).addClass("active").
  • Form validation errors$("input:invalid").addClass("error") to apply error styling from CSS.
  • Show/hide with CSS$(".panel").addClass("visible") where .visible { display: block; }.
  • Animation hooks$("div").addClass("animate-in") to trigger CSS transitions or keyframes.
  • Row highlighting$("tr").click(function(){ $(this).addClass("selected-row"); }).
  • Delegated styling$(this).parent().addClass("active-group") after a child click (see .parent() tutorial).

🧠 How .addClass() Updates Elements

1

Match elements

jQuery object holds one or more DOM nodes to update.

Input
2

Resolve class names

String, array, or callback produces class name(s) per element.

Parse
3

Update class attribute

New names append to existing classes — nothing removed.

DOM
4

Styles apply

CSS rules for new classes take effect — return same jQuery object for chaining.

📝 Notes

  • Available since jQuery 1.0 — core class manipulation API.
  • Does not replace existing classes — only appends new class names.
  • Array argument supported since jQuery 3.3; callback since 1.4.
  • Callback receives (index, currentClass) — return string or array (3.3+).
  • SVG and XML elements supported since jQuery 1.12.
  • Returns the original jQuery object for chaining — e.g. .addClass("x").fadeIn().

Browser Support

.addClass() has been part of jQuery since 1.0+. Array arguments arrived in 3.3+; SVG/XML support in 1.12+. It relies on standard class attribute manipulation with no browser-specific quirks beyond jQuery itself.

jQuery 1.0+

jQuery .addClass()

Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. Native equivalent: element.classList.add() — jQuery adds collection semantics, callback forms, and older-browser consistency.

100% With jQuery loaded
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.addClass() Universal

Bottom line: Safe in any jQuery project. Prefer .addClass() for stylesheet classes; use .css() for one-off inline values.

Conclusion

The jQuery .addClass() method appends one or more CSS class names to each matched element. It is the standard way to turn stylesheet-defined styles on at runtime — without touching inline properties or wiping existing classes.

Remember the official demo: $("p").last().addClass("selected") highlights one paragraph while preserving its other classes. Chain .removeClass() when switching exclusive states, reach for .toggleClass() for simple on/off, and use .css() only when you need dynamic inline values.

💡 Best Practices

✅ Do

  • Define reusable styles in CSS and toggle them with .addClass()
  • Chain .removeClass() before .addClass() for exclusive states
  • Use the array form when class names come from a JavaScript array (3.3+)
  • Use the callback form when each element needs a unique class
  • Keep class names semantic — .active, .error, not .red-text

❌ Don’t

  • Expect .addClass() to remove or replace existing classes
  • Use .addClass() for one-off pixel values — use .css() instead
  • Add duplicate classes repeatedly in a loop without checking — jQuery deduplicates, but it is wasteful
  • Mix too many single-purpose classes — consolidate in your stylesheet
  • Forget that .toggleClass() may be simpler for binary on/off states

Key Takeaways

Knowledge Unlocked

Five things to remember about .addClass()

Append classes — never replace.

5
Core concepts
02

.removeClass()

Strip

Compare
03

.toggleClass()

Flip

Compare
[] 04

Array

3.3+

Syntax
fn 05

Callback

Per item

1.4+

❓ Frequently Asked Questions

.addClass() appends one or more CSS class names to each element in the current jQuery collection. It updates the element's class attribute so stylesheet rules for those classes apply — without changing HTML content or inline style properties.
No. .addClass() only adds new class names alongside whatever is already on the element. To remove old classes first, chain .removeClass() or use .toggleClass() when you want on/off behavior.
.addClass() appends class names for stylesheet-driven styling. .css() sets inline style properties. .removeClass() strips classes. .toggleClass() adds a class when missing and removes it when present — useful for switches without a separate remove step.
Yes. Pass a space-separated string — addClass('selected highlight') — or since jQuery 3.3 an array — addClass(['selected', 'highlight']). jQuery adds every listed class to each matched element.
Since jQuery 1.4, you can pass a function: addClass(function(index, currentClass) { return 'item-' + index; }). jQuery calls it once per element and adds the returned string. Since 3.3 the callback may return an array of class names.
Yes, since jQuery 1.12 .addClass() supports SVG and XML elements in addition to HTML. Class manipulation on SVG follows the same API — useful for toggling states on icons and vector graphics.
Did you know?

jQuery’s .addClass() has existed since version 1.0 — one of the earliest DOM manipulation methods. The callback form (1.4+) lets you generate class names per element without a manual loop, and since 1.12 it works on SVG elements too — so you can add .highlighted to an icon path the same way you would a <div>.

Next: .hasClass()

Learn how to test whether matched elements have a CSS class.

.hasClass() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful