jQuery Select Element by ID and Class
Combining an ID and class selector in jQuery allows you to target a specific DOM element with high precision. This guide explains the exact syntax required to select an element containing both an ID and a class, highlights common syntax pitfalls, and covers alternative methods for checking class membership programmatically.
The Basic Syntax
To select an element that has both a specific ID and a specific class
on the exact same element, chain the ID selector (#) and
the class selector (.) together without any spaces:
$('#yourID.yourClass')Because an ID should be unique on a web page, simply using
$('#yourID') is usually sufficient. However, appending the
class allows you to verify that the element currently possesses that
specific class before applying any actions.
Practical Example
Consider the following HTML markup:
<div id="notification" class="alert-box success">
Action completed successfully.
</div>
<div id="profile" class="hidden">
User Profile Content
</div>To target the #notification element only when it
contains the success class:
// Target the element and apply styling or behavior
$('#notification.success').fadeIn();If the #notification element does not have the
success class, jQuery will return an empty set and execute
no actions.
Crucial Note: Avoid Whitespace
The presence of a space between the ID and the class fundamentally changes how the selector works:
- No space (
$('#myID.myClass')): Targets an element that has the IDmyIDand the classmyClasssimultaneously. - With a space (
$('#myID .myClass')): Targets a child or descendant element with the classmyClasslocated inside the parent element with IDmyID.
Alternative Approach: Using
.hasClass()
If your goal is to execute conditional logic based on whether an
element with a specific ID contains a certain class, use jQuery’s
.hasClass() method instead:
if ($('#notification').hasClass('success')) {
// Logic executed if the class is present
console.log('The notification is in success state.');
}This method is often preferred in JavaScript logic where you need to branch execution paths rather than directly chain DOM operations.