How to Select Elements by Attribute Value in jQuery

Selecting elements based on their attribute values is a fundamental task in jQuery, accomplished using the attribute equals selector syntax: [attribute="value"]. This guide explains how to use this selector to target HTML elements precisely, demonstrates practical code examples for common attributes like name, type, and custom data-* attributes, and covers how to handle special characters.

The Attribute Equals Selector Syntax

jQuery utilizes CSS-style selectors to find elements. To target an element where an attribute matches an exact string, use the following syntax:

$('[attribute="value"]')

You can prefix this selector with an element tag name to narrow down the search and improve query performance:

$('element[attribute="value"]')

Basic Examples

1. Selecting by Input Type or Name

A common use case is targeting specific form controls.

// Select all input elements with type="text"
$('input[type="text"]').addClass('highlight');

// Select an input with a specific name attribute
$('input[name="username"]').val('JohnDoe');

You can target anchor tags directing to a specific URL:

// Select a link pointing to a specific page
$('a[href="https://example.com"]').attr('target', '_blank');

3. Selecting by Custom Data Attributes

HTML5 data-* attributes can be selected using the same syntax:

// Select an element with data-status="active"
$('div[data-status="active"]').show();

// Select an element with a specific data-id
$('li[data-id="101"]').remove();

Selecting with Multiple Attributes

You can chain attribute selectors together to match elements that satisfy multiple conditions simultaneously:

// Select an input that has type="checkbox" AND name="newsletter"
$('input[type="checkbox"][name="newsletter"]').prop('checked', true);

Handling Quotes and Special Characters

While quotes around the value are optional in simple cases, they are mandatory if the value contains spaces, punctuation, or special characters. It is best practice to always wrap attribute values in quotation marks:

// Correctly wrapped in quotes to handle spaces
$('input[value="Save Changes"]').prop('disabled', true);

If your attribute value contains quotes or backslashes, escape them using a backslash (\):

// Escaping internal quotes
$('input[value="Say \\"Hello\\""]').css('color', 'green');