How to get an element by its href in jQuery?
To quickly fetch an anchor element by its href
in jQuery, use the attribute equals selector $('a[href="URL"]')
:
Exploring the href attribute with jQuery
Exact href value
This will get you the first anchor tag with the exact href https://google.com
.
Starts with a specific URL
To gather elements with href attribute that starts with a specific piece of URL, use the attribute-starts-with selector ^=
.
Contains a string
To get elements with href containing a certain string, use the attribute-contains selector *=
.
Complex scenarios and those sweet selectors!
Combining attribute selectors
You can combine several selectors for more refined results.
Exclusion management with :not
selector
The not
pseudo-class can be extremely helpful when you need to exclude certain elements:
In the above snippet, we're ignoring all those pesky PDF links!
Handling dynamic environments
Managing asynchronous content
In cases where content may be loaded asynchronously, direct queries might fail. We have a solution though, make use of delegation via .on()
:
Dealing with case sensitivity of URL
Browsers might change the case of URLs but jQuery's attribute selectors are strictly case-sensitive. Here is a neat trick to tackle this issue:
Maximizing Performance
Scope your jQuery selection
Direct attribute searches can be costly, so reduce your search scope:
Cache to rescue
Cache your jQuery results if you are planning to reuse them:
Was this article helpful?