How to Select Elements by Class in jQuery
Selecting elements by class name in jQuery is a fundamental technique for manipulating groups of HTML elements efficiently. This guide explains the correct syntax for using the jQuery class selector, illustrates how to target single or multiple classes, and provides practical examples to help you quickly apply styles, bind events, or modify content across your web pages.
The Basic Syntax
To select elements by their class name in jQuery, you use the
standard CSS class selector syntax, which prefixes the class name with a
period (.):
$(".className")When you pass this selector into the jQuery function
($()), jQuery traverses the DOM and returns a jQuery object
containing all elements that have the specified class.
Practical Example
Consider the following HTML markup:
<p class="highlight">Paragraph 1</p>
<p>Paragraph 2</p>
<p class="highlight">Paragraph 3</p>To target only the paragraphs with the highlight class
and change their text color to red, use:
$(".highlight").css("color", "red");Both Paragraph 1 and Paragraph 3 will update immediately, while Paragraph 2 remains unchanged.
Advanced Class Selection
You can refine your queries by combining the class selector with other selectors:
Specific HTML Element with Class: To select only
<p>tags with the classintro, combine the element name and the class without spaces:$("p.intro")Multiple Classes on the Same Element: To select an element that must have both
btnandbtn-primaryclasses:$(".btn.btn-primary")Multiple Class Selectors (OR): To select elements that have either one class or another, separate them with a comma:
$(".header, .footer")Descendant Elements: To select elements with the class
iteminside an element with the IDmenu, separate them with a space:$("#menu .item")
Summary
The correct jQuery syntax to select elements by class name is
$(".className"). Always remember to include the leading dot
(.), as omitting it causes jQuery to look for standard HTML
element tags instead of class attributes.