jQuery Attribute Ends With Selector for href
This article provides a concise overview of using jQuery's "attribute
ends with" selector to target anchor tags based on the termination of
their href values. By utilizing the $=
operator, developers can efficiently select and manipulate links
pointing to specific file extensions, domains, or paths without scanning
the entire URL string manually.
The Specific Syntax
The jQuery syntax for the attribute ends with selector applied to an
href attribute is:
$('a[href$="value"]')a: Specifies the HTML anchor tag. You can omit this to target any element containing anhrefattribute (e.g.,[href$="value"]), but specifying the tag improves performance.href: The attribute you want to inspect.$=: The selector operator that signifies "ends with.""value": The exact substring you expect to find at the very end of the attribute's value. Wrapping the value in quotes is recommended to prevent syntax errors with special characters.
Practical Example
To select all links on a page that point to PDF files and apply a distinct CSS style or icon, use the following code:
// Target all anchor tags where the href attribute ends with ".pdf"
$('a[href$=".pdf"]').css({
"color": "red",
"font-weight": "bold"
});If you need to handle multiple extensions, such as targeting both
.jpg and .png image links, you can combine
selectors separated by commas:
$('a[href$=".jpg"], a[href$=".png"]').addClass('image-link');Important Considerations
- Case Sensitivity: The
$=selector is case-sensitive in standard jQuery and CSS implementations. A link ending in.PDFwill not be matched by[href$=".pdf"]. If your source HTML contains inconsistent casing, you may need to normalize the attributes or use a.filter()function with a case-insensitive regular expression. - Anchor Fragments and Query Strings: The selector
matches the literal end of the attribute string. If a URL contains query
parameters (e.g.,
document.pdf?version=2) or anchor hashes (e.g.,document.pdf#page=1), the attribute will not end in.pdf, and the selector will not match the element.