jQuery Select Elements With a Specific Attribute

This article explains how to select HTML elements that possess a specific attribute using jQuery. In web development, targeting elements based on attributes—such as custom data-* tags, form states, or standard HTML attributes—is a common task. By using jQuery's built-in CSS attribute selectors, you can quickly locate and manipulate DOM elements without needing unique classes or IDs.

The Has Attribute Selector: [attribute]

To select elements simply because they have a specific attribute, regardless of what value that attribute holds, use the [attribute] selector enclosed in square brackets.

$('[attributeName]')

For example, to select every element on the page that has a data-role attribute:

$('[data-role]').css('border', '1px solid blue');

Limiting by Element Type

You can combine the attribute selector with standard HTML tag names to target only specific elements. This is faster and avoids selecting unrelated tags.

// Selects only <input> elements that have the "required" attribute
$('input[required]').addClass('highlight');

// Selects only <a> tags that have a "target" attribute
$('a[target]').addClass('external-link');

Selecting by Attribute Value

If you need to match elements where the attribute has a specific value or pattern, jQuery supports standard CSS attribute matchers:

  • Exact Match ([attribute="value"]): Matches elements where the attribute equals the specified string.
    $('input[type="text"]')
  • Contains Word ([attribute~="value"]): Matches elements where the attribute value contains a specific whitespace-separated word.
    $('a[rel~="nofollow"]')
  • Starts With ([attribute^="value"]): Matches elements where the attribute starts with the given string.
    $('a[href^="https://"]')
  • Ends With ([attribute$="value"]): Matches elements where the attribute ends with the given string.
    $('img[src$=".png"]')
  • Contains Substring ([attribute*="value"]): Matches elements where the attribute value contains the string anywhere within it.
    $('div[class*="menu"]')

Selecting by Multiple Attributes

You can chain multiple attribute selectors together to find elements that satisfy all specified conditions:

// Selects <input> elements that have both a "required" attribute and type="email"
$('input[type="email"][required]').focus();