How to Get Attribute Value Using jQuery attr()
Retrieving HTML element attribute values is a fundamental task in DOM
manipulation using jQuery. This guide demonstrates how to use the jQuery
attr() method to read specific attribute values—such as
href, src, title, or custom
attributes—from targeted elements with practical code examples and best
practices.
The Syntax
To get the value of an attribute, pass the attribute name as a string
to the attr() method:
$(selector).attr(attributeName);selector: The jQuery selector identifying the target HTML element.attributeName: A string representing the name of the attribute you want to access (e.g.,'href','src','id').
Basic Example
Consider the following HTML link element:
<a id="download-link" href="https://example.com/file.zip" target="_blank">Download File</a>To extract the href and target attributes
using jQuery:
$(document).ready(function() {
// Get the 'href' attribute
var fileUrl = $('#download-link').attr('href');
console.log(fileUrl); // Outputs: "https://example.com/file.zip"
// Get the 'target' attribute
var linkTarget = $('#download-link').attr('target');
console.log(linkTarget); // Outputs: "_blank"
});Key Behaviors to Keep in Mind
Returns Value from the First Element Only: When the selector matches multiple elements,
.attr(attributeName)retrieves the value from only the first element in the matched set. To get attributes from all matched elements, iterate through them using the.each()method.Undefined for Missing Attributes: If the specified attribute does not exist on the selected element,
.attr()returnsundefined. You can use this to check for an attribute's presence:var title = $('#download-link').attr('title'); if (typeof title !== 'undefined' && title !== false) { console.log("Title found: " + title); } else { console.log("Title attribute does not exist."); }attr()vs.prop(): Useattr()to read static HTML attributes defined in the markup (such ashref,src,rel, or custom attributes). Use the jQueryprop()method for intrinsic DOM properties that change dynamically, such aschecked,selected, ordisabled.