jQuery Attribute Contains Word vs Contains Selector
This article explains the core differences between jQuery's Attribute
Contains Word Selector ([name~="value"]) and the standard
Attribute Contains Selector ([name*="value"]). While both
selectors filter elements based on attribute strings, they differ
fundamentally in how they handle boundaries: the contains word selector
requires an exact, whitespace-delimited word match, whereas the standard
contains selector matches any substring regardless of where it appears
inside the attribute.
The Attribute
Contains Selector: [attribute*="value"]
The standard Attribute Contains Selector matches elements if the specified attribute contains the target string anywhere within its value. It treats the attribute value as a continuous sequence of characters.
- Syntax:
$("element[attribute*='value']") - Matching behavior: It matches substrings directly, even if they are embedded within larger words or attached to hyphens and underscores.
- Example:
// Target: <div class="nav-button-primary"></div> $("[class*='button']"); // Matches successfully $("[class*='ton']"); // Matches successfully
The
Attribute Contains Word Selector: [attribute~="value"]
The Attribute Contains Word Selector matches elements only if the specified attribute contains the target string as a distinct, standalone word surrounded by whitespace.
- Syntax:
$("element[attribute~='value']") - Matching behavior: The target string must be separated from other text by spaces, mimicking how individual class names are parsed in standard HTML. It will not match substrings attached to other characters or hyphens.
- Example:
// Target: <div class="nav button primary"></div> $("[class~='button']"); // Matches successfully // Target: <div class="nav-button primary"></div> $("[class~='button']"); // Does NOT match (separated by a hyphen, not a space)
Key Differences at a Glance
| Feature | Attribute Contains (*=) |
Attribute Contains Word
(~=) |
|---|---|---|
| Match Condition | Substring match | Whole word match |
| Delimiter | None required | Whitespace-delimited |
| Partial Matches | Matches partial segments (e.g., "port" in "transport") | Rejects partial segments |
| Hyphenated Strings | Matches within hyphenated strings (e.g., "red" in "dark-red") | Treats hyphenated strings as single words and fails to match |
Note on the
:contains() Text Selector
Neither of these attribute selectors should be confused with jQuery's
:contains("text") selector. While
[attr*="value"] and [attr~="value"] evaluate
DOM attributes (such as id, class,
rel, or title), the :contains()
pseudo-class searches through the textual content directly inside an
element.