How to Get All Elements with a Specific Href Attribute Value in JavaScript
In web development, there are countless scenarios where you might need to target HTML elements based on specific attributes. One common task is selecting all links (<a> tags) that point to a particular URL via their href attribute. Whether you’re validating links, modifying styles, or tracking user interactions, knowing how to efficiently retrieve these elements is a fundamental skill.
This blog will guide you through three methods to get all elements with a specific href value using vanilla JavaScript. We’ll cover everything from basic exact matches to advanced partial matches, common pitfalls, and performance considerations. By the end, you’ll be equipped to handle any href selection task with confidence.
Table of Contents#
- Understanding the
hrefAttribute- 1.1 What is
href? - 1.2 Attribute vs. Property: Key Difference
- 1.1 What is
- Method 1: Using
document.querySelectorAll()- 2.1 Syntax and Attribute Selectors
- 2.2 Exact Match Example
- 2.3 Partial Matches (Contains, Starts With, Ends With)
- 2.4 Handling Special Characters in
href - 2.5 Pros and Cons
- Method 2: Using
getElementsByTagName()+ Filtering- 3.1 How It Works
- 3.2 Example: Filtering Anchor Tags
- 3.3 Attribute vs. Property in Filtering
- 3.4 Pros and Cons
- Method 3: Using
getElementsByClassName()(If Applicable) - Common Pitfalls and Solutions
- 5.1 Relative vs. Absolute URLs
- 5.2 Case Sensitivity
- 5.3 Special Characters in
href
- Performance Considerations
- Practical Use Case: Modifying Links Dynamically
- Comparison of Methods
- Conclusion
- References
Understanding the href Attribute#
What is href?#
The href attribute is used in anchor tags (<a>) to specify the URL of the page the link points to. It can also link to email addresses (mailto:), phone numbers (tel:), or internal page sections (#section-id). Examples include:
<a href="https://example.com">External Link</a>
<a href="/about">Internal Page</a>
<a href="#contact">Section Anchor</a> Attribute vs. Property: Key Difference#
When working with href, it’s critical to distinguish between the attribute and the property:
- Attribute: The literal string value defined in the HTML (e.g.,
<a href="/about">has anhrefattribute of"/about"). Useelement.getAttribute('href')to access it. - Property: The resolved URL value (e.g., if the page is hosted at
https://site.com, thehrefproperty of<a href="/about">becomes"https://site.com/about"). Access it directly viaelement.href.
This distinction matters because methods like querySelectorAll use the attribute value, while direct property access uses the resolved URL.
Method 1: Using document.querySelectorAll()#
document.querySelectorAll() is the most versatile and recommended method for selecting elements by attributes. It accepts a CSS selector string and returns a static NodeList of matching elements.
Syntax and Attribute Selectors#
To target href, use CSS attribute selectors. The basic syntax is:
const elements = document.querySelectorAll('[href="target-value"]'); Attribute selectors support more than exact matches. Here are common variations:
| Selector | Description | Example |
|---|---|---|
[href="value"] | Exact match (case-sensitive) | [href="https://example.com"] |
[href*="value"] | Contains "value" anywhere in the attribute | [href*="example"] (matches example.com, my-example) |
[href^="value"] | Starts with "value" | [href^="https://"] (external links) |
[href$="value"] | Ends with "value" | [href$=".pdf"] (PDF links) |
Exact Match Example#
Suppose your HTML has these links:
<a href="https://example.com">Home</a>
<a href="/about">About</a>
<a href="https://example.com">Blog</a>
<a href="https://google.com">Google</a> To select all links with href="https://example.com":
// Select elements with exact href match
const exampleLinks = document.querySelectorAll('[href="https://example.com"]');
// Log results (NodeList of 2 elements)
console.log(exampleLinks); // NodeList(2) [a, a] Partial Match Examples#
Contains a Substring#
To select all links containing "example" in their href:
const exampleSubstringLinks = document.querySelectorAll('[href*="example"]');
// Matches: https://example.com, https://example.com/blog Starts With a Value#
To select all external links (starting with https://):
const externalLinks = document.querySelectorAll('[href^="https://"]'); Ends With a Value#
To select all PDF links:
const pdfLinks = document.querySelectorAll('[href$=".pdf"]'); Handling Special Characters in href#
If the href contains special characters (e.g., spaces, quotes, or backslashes), escape them in the selector:
- Spaces: Use the literal space (e.g.,
[href="my link"]for<a href="my link">). - Quotes: Escape with a backslash (e.g.,
[href="a\"b"]for<a href='a"b'>). - Backslashes: Escape twice (e.g.,
[href="a\\b"]for<a href="a\b">).
Pros and Cons#
| Pros | Cons |
|---|---|
| Supports complex selectors (exact/partial matches). | Returns a static NodeList (doesn’t update if DOM changes). |
| Easy to read and write. | Slightly slower than live collections for very large DOMs (negligible for most cases). |
Method 2: Using getElementsByTagName() + Filtering#
If you need a live collection (updates automatically as the DOM changes) or want more control over filtering, use document.getElementsByTagName('a') to get all links, then filter by href attribute.
How It Works#
- Use
getElementsByTagName('a')to retrieve all<a>tags as anHTMLCollection(live). - Convert the collection to an array (since
HTMLCollectionlacks array methods likefilter). - Filter the array by checking the
hrefattribute withgetAttribute('href').
Example: Filtering Anchor Tags#
Using the same HTML as before:
<a href="https://example.com">Home</a>
<a href="/about">About</a>
<a href="https://example.com">Blog</a>
<a href="https://google.com">Google</a> Select links with href="https://example.com":
// Step 1: Get all <a> tags (live HTMLCollection)
const allLinks = document.getElementsByTagName('a');
// Step 2: Convert to array (to use filter)
const linksArray = Array.from(allLinks);
// Step 3: Filter by href attribute
const exampleLinks = linksArray.filter(link => {
return link.getAttribute('href') === 'https://example.com';
});
console.log(exampleLinks); // Array(2) [a, a] Attribute vs. Property in Filtering#
To filter by the resolved URL (property) instead of the attribute, use link.href instead of getAttribute:
// Filter by resolved URL (e.g., matches relative paths resolved to absolute)
const resolvedExampleLinks = linksArray.filter(link => {
return link.href === 'https://example.com'; // Uses property, not attribute
}); Pros and Cons#
| Pros | Cons |
|---|---|
| Returns a live HTMLCollection (auto-updates with DOM). | Requires manual filtering (extra code). |
| Slightly faster for large DOMs. | Less readable than querySelectorAll. |
Method 3: Using getElementsByClassName() (If Applicable)#
If your links with the target href share a class (e.g., <a class="external-link" href="https://example.com">), use getElementsByClassName() for faster selection:
// Select elements by class, then filter by href
const externalLinks = document.getElementsByClassName('external-link');
const exampleLinks = Array.from(externalLinks).filter(link => {
return link.getAttribute('href') === 'https://example.com';
}); This is efficient but only useful if the links have a shared class.
Common Pitfalls and Solutions#
1. Relative vs. Absolute URLs#
Problem: A link with href="/about" has an attribute value of "/about" but a resolved property value of "https://site.com/about".
Solution: Use getAttribute('href') for the literal attribute, or link.href for the resolved URL.
2. Case Sensitivity#
Problem: Attribute selectors are case-sensitive. <a href="HTTPS://EXAMPLE.COM"> won’t match [href="https://example.com"].
Solution: Normalize case with toLowerCase():
const caseInsensitiveLinks = linksArray.filter(link => {
return link.getAttribute('href').toLowerCase() === 'https://example.com';
}); 3. Performance with Large DOMs#
Problem: querySelectorAll creates a static snapshot, which can be slow for 10,000+ links.
Solution: Use getElementsByTagName (live collection) for very large DOMs, as it avoids snapshotting all elements at once.
Performance Considerations#
| Method | Speed (Large DOM) | Use Case |
|---|---|---|
querySelectorAll | Good | Most cases (static selection, readability). |
getElementsByTagName | Better | Live collections or very large DOMs. |
Practical Use Case: Modifying Links Dynamically#
Let’s say you want to highlight all links pointing to https://example.com by changing their color to red:
<!-- HTML -->
<a href="https://example.com">Home</a>
<a href="/about">About</a>
<a href="https://example.com">Blog</a> // Select links and modify style
const exampleLinks = document.querySelectorAll('[href="https://example.com"]');
exampleLinks.forEach(link => {
link.style.color = 'red';
link.style.fontWeight = 'bold';
}); This will turn all matching links red and bold.
Comparison of Methods#
| Method | Returns | Static/Live | Best For |
|---|---|---|---|
querySelectorAll | NodeList | Static | Exact/partial matches, readability. |
getElementsByTagName | HTMLCollection | Live | Large DOMs, dynamic content. |
getElementsByClassName | HTMLCollection | Live | Links with shared classes. |
Conclusion#
To get elements with a specific href value:
- Use
document.querySelectorAll('[href="value"]')for most cases (simple, flexible, and readable). - Use
getElementsByTagName('a')+ filtering if you need a live collection or better performance with large DOMs. - Always consider the difference between
hrefattributes (literal) and properties (resolved URLs).
With these methods, you can confidently target and manipulate links in any web project.