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#

  1. Understanding the href Attribute
    • 1.1 What is href?
    • 1.2 Attribute vs. Property: Key Difference
  2. 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
  3. 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
  4. Method 3: Using getElementsByClassName() (If Applicable)
  5. Common Pitfalls and Solutions
    • 5.1 Relative vs. Absolute URLs
    • 5.2 Case Sensitivity
    • 5.3 Special Characters in href
  6. Performance Considerations
  7. Practical Use Case: Modifying Links Dynamically
  8. Comparison of Methods
  9. Conclusion
  10. 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 an href attribute of "/about"). Use element.getAttribute('href') to access it.
  • Property: The resolved URL value (e.g., if the page is hosted at https://site.com, the href property of <a href="/about"> becomes "https://site.com/about"). Access it directly via element.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:

SelectorDescriptionExample
[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#

ProsCons
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#

  1. Use getElementsByTagName('a') to retrieve all <a> tags as an HTMLCollection (live).
  2. Convert the collection to an array (since HTMLCollection lacks array methods like filter).
  3. Filter the array by checking the href attribute with getAttribute('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#

ProsCons
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#

MethodSpeed (Large DOM)Use Case
querySelectorAllGoodMost cases (static selection, readability).
getElementsByTagNameBetterLive collections or very large DOMs.

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#

MethodReturnsStatic/LiveBest For
querySelectorAllNodeListStaticExact/partial matches, readability.
getElementsByTagNameHTMLCollectionLiveLarge DOMs, dynamic content.
getElementsByClassNameHTMLCollectionLiveLinks 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 href attributes (literal) and properties (resolved URLs).

With these methods, you can confidently target and manipulate links in any web project.

References#