Using the jQuery Attribute Starts With Selector
This article explains how the jQuery attribute starts with selector functions to target DOM elements whose specified attribute begins with a particular string. You will learn the exact syntax required to combine this selector with specific element names, understand how the matching mechanism works under the hood, and see clear examples demonstrating how to narrow down queries to specific HTML tags for cleaner code and improved DOM traversal performance.
Understanding the Syntax
The jQuery attribute starts with selector uses the ^=
operator inside square brackets. To restrict the search to a specific
HTML element type, you prepend the tag name directly before the opening
bracket:
$("elementName[attribute^='value']")elementName: The specific HTML tag you want to target (such asinput,div,a, orbutton).attribute: The name of the HTML attribute to inspect (such asid,name,class, ordata-*).^=: The "starts with" operator.'value': The string prefix that the attribute's value must begin with.
How Element-Specific Targeting Works
When you omit the element name (e.g.,
$("[id^='user-']")), jQuery must evaluate every element in
the DOM tree that carries that attribute. By qualifying the selector
with a specific element name—such as
$("div[id^='user-']")—the browser first isolates the
specified tag type using native methods like
getElementsByTagName(). Only those matching tags are then
inspected for the attribute condition.
For example, consider the following HTML structure:
<input type="text" name="user_first_name" />
<input type="text" name="user_last_name" />
<div name="user_profile_box"></div>
<a href="#" name="user_link">Profile</a>If the goal is to apply styling or an event handler exclusively to
the <input> elements whose name begins
with "user_", target the tag explicitly:
$('input[name^="user_"]').addClass("highlight-field");In this case:
- jQuery looks only at
<input>elements. - It checks the
nameattribute of each input. - The
<div name="user_profile_box">and<a name="user_link">are automatically ignored, even though theirnameattributes begin with the same prefix.
Key Considerations
- Case Sensitivity: Attribute values are generally
case-sensitive in jQuery selectors. An attribute value of
User_will not match a query looking foruser_. - Quotes: Always wrap the target string in quotes (single or double) inside the brackets. While sometimes optional for simple alphanumeric strings, quotes prevent syntax errors when dealing with hyphens, underscores, or symbols.
- Combining with Other Selectors: You can chain this
selector with other jQuery filters. For instance,
$("input[type='text'][name^='billing_']")targets only text inputs where the name begins with"billing_".