Keywords: JavaScript | HTML | href attribute | DOM manipulation | frontend development
Abstract: This article provides an in-depth exploration of two distinct approaches for accessing href attributes in anchor tags using JavaScript: direct property access returns the full URL, while getAttribute method retrieves the original attribute value. Through detailed technical analysis and code examples, it explains how HTML parsing behavior affects href values and offers best practice recommendations for real-world development scenarios. The article also incorporates relevant cases from AngularJS to demonstrate href value handling strategies across different framework environments.
HTML Anchor Tag href Attribute Parsing Mechanism
In web development, handling the href attribute of anchor tags (<a>) is a common yet frequently misunderstood technical aspect. When developers expect to retrieve the original href value defined in HTML through JavaScript, they often encounter unexpected results.
Difference Between href Property and href Attribute
HTML DOM provides two distinct methods for accessing href values in anchor tags, each returning different results:
// Get the fully resolved URL
document.getElementById("anchor").href; // Returns: http://example.com/sec/IF00.html
// Get the original attribute value
document.getElementById("anchor").getAttribute("href"); // Returns: sec/IF00.html
This discrepancy stems from HTML parser behavior. When browsers parse HTML documents, they convert relative URLs to absolute URLs, and this conversion is reflected in the element's href property while leaving the original HTML attribute value unchanged.
Practical Application Scenarios
Consider the following common use case:
<a onclick="return follow(this);" href="sec/IF00.html">Click Me</a>
<script>
baseURL = 'http://www.someotherdomain.com/';
function follow(item) {
// Incorrect approach: gets full URL
// location.href = baseURL + item.href;
// Correct approach: gets original attribute value
location.href = baseURL + item.getAttribute("href");
}
</script>
Using item.href leads to incorrect URL concatenation because item.href already contains the full path including the current domain. In contrast, item.getAttribute("href") returns the original sec/IF00.html value, which is exactly what we need.
Handling Strategies Across Framework Environments
In modern frontend frameworks, href attribute handling can become more complex. For example, in AngularJS, the framework may modify default link behavior:
// Custom directive handling in AngularJS
angular.module('App').directive('a', function($location) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// Get original href value
var originalHref = attrs.href;
// Framework-specific processing logic
if (originalHref && originalHref.charAt(0) === '#') {
// Handle anchor links
element.on('click', function(event) {
event.preventDefault();
$location.hash(originalHref.slice(1));
scope.$apply();
});
}
}
};
});
Performance and Compatibility Considerations
When choosing methods for retrieving href values, consider the following factors:
- Performance: The
getAttribute()method is generally faster than direct property access since it doesn't require URL parsing - Compatibility: Both methods are well-supported across all modern browsers
- Maintainability: Using
getAttribute()makes code intentions more explicit
Best Practice Recommendations
Based on the above analysis, the following best practices are recommended:
- Always use
getAttribute("href")when you need the original href value as defined in HTML - Use the element's
hrefproperty when you need the browser-resolved full URL - In framework environments, understand the framework's specific handling of link behavior
- For dynamically generated links, ensure proper value retrieval after setting href attributes
// Best practice example
function handleAnchorClick(anchorElement) {
var originalHref = anchorElement.getAttribute("href");
var resolvedHref = anchorElement.href;
// Choose which value to use based on requirements
if (needsOriginalValue) {
return originalHref;
} else {
return resolvedHref;
}
}
By understanding the dual nature of href attributes, developers can avoid common pitfalls and write more robust, maintainable code.