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

  1. 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.

  2. Undefined for Missing Attributes: If the specified attribute does not exist on the selected element, .attr() returns undefined. 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.");
    }
  3. attr() vs. prop(): Use attr() to read static HTML attributes defined in the markup (such as href, src, rel, or custom attributes). Use the jQuery prop() method for intrinsic DOM properties that change dynamically, such as checked, selected, or disabled.