jQuery Data vs Attr

jQuery-Data-vs-Attr-Feature-Image.jpg

When you work with jQuery, two methods you’ll use often are .attr() and .data(). Both help you store and retrieve values from DOM elements, yet they behave very differently behind the scenes. Many beginners assume they’re interchangeable, but understanding the difference between attr and data in jQuery is important if you want clean, predictable, and maintainable code.

In this blog, we’ll break down how jQuery attributes and data methods work, where the values are stored, and how they affect the DOM. You’ll also see practical jQuery .attr() examples and jQuery .data() examples so you can understand exactly when to use attr or data in jQuery. By the end, you’ll be able to choose the right method confidently and avoid common mistakes developers make when manipulating DOM data.

Table of Contents:

What is .attr() in jQuery?

You can use the .attr() method to get or set an element’s attributes. Example of attributes: id, class, href, src, and alt   

Syntax:

// Get an attribute value
var value = $("#element").attr("attribute-name");

// Set an attribute value
$("#element").attr("attribute-name", "value");

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Image Source with jQuery</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        #image {
            width: 300px;
            height: auto;
            border: 2px solid #333;
            display: block;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <h2>Click the button to change the image</h2>
    <img id="image" src="https://intellipaat.com/blog/wp-content/uploads/2025/02/What-is-HTML-Feature-Image.jpg" alt="Sample Image">
    <button id="changeImage">Change Image</button>

    <script>
        $(document).ready(function() {
            var imageSrc = $("#image").attr("src");
            console.log("Initial src:", imageSrc); 
            $("#changeImage").click(function() {
                $("#image").attr("src", "https://intellipaat.com/blog/wp-content/uploads/2023/04/A-guide-to-HTML-Link.png");
                console.log("Updated src:", $("#image").attr("src")); 
            });
        });
    </script>
</body>
</html>

Output:

What is .attr() in jQuery Output

Explanation: In this code, the source of the image is changed using jQuery. The first image, which is set to the src attribute, is displayed, and after clicking the button, the src attribute gets updated to the new image URL.

Key Features of .attr()

  • You can use the .attr() to interact with actual HTML attributes in the DOM.
  • You can use it to retrieve the value as it is defined in the markup.
  • It updates the attribute in the DOM when set.

What is .data() in jQuery?

You can save and access the data from the DOM element using the .data() method. The data is not connected to the HTML attribute of the element. You can see it is stored separately in the jQuery.

Syntax:

// Set data
$("#element").data("key", "value");

// Get data
var value = $("#element").data("key");

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery .data() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        #box {
            width: 200px;
            height: 100px;
            background-color: lightblue;
            text-align: center;
            line-height: 100px;
            font-size: 18px;
            border: 2px solid #333;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h2>Click the box to display stored data</h2>
    <div id="box" data-company="Intellipaat">Click Me</div>

    <script>
        $(document).ready(function() {
            var company = $("#box").data("company");
            console.log("Company:", company); 
            $("#box").data("course", "Web Development");
            $("#box").click(function() {
                var storedCompany = $(this).data("company");
                var storedCourse = $(this).data("course");
                alert("Company: " + storedCompany + "\nCourse: " + storedCourse);
            });
        });
    </script>
</body>
</html>

Output:

What is .data() in jQuery Output

Explanation: This code uses jQuery’s .data() method to store and retrieve custom data associated with a <div> element. It preloads data-company and dynamically adds data-course. Clicking the <div> shows both stored values in an alert.

Key Features of .data()

  • The data stored using .data() is cached by jQuery and does not reflect changes in the HTML markup.
  • .data() retrieves values stored using the data-* attribute but does not modify the actual attribute.
  • .data() allows for storing JavaScript objects and complex data types.

Differences Between .attr() and .data()

Before we dive into the details of when to use .attr() vs .data(), here’s a quick comparison that highlights the difference between attr and data in jQuery.

Feature .attr() .data()
Interaction with DOMDirectly interact with attributes in the DOMIt uses jQuery’s internal data storage
Modification in the actual attributeYesNo
Retrieving value fromHTML attributes jQuery data cache
Does it support complex data typesNoyes
Does it persist after DOM modificationYesNo(unless reloaded from markup)

When to Use .attr() and .data()

You can use .attr() when:

  • You need to get or set standard HTML attributes such as id, class, href, src, or alt.
  • You need to ensure changes reflect in the actual HTML markup.
  • You are working with Boolean attributes such as checked, disabled, or read-only.

Example: Changing the href attribute of a link

$("#link").attr("href", "https://example.com");

You can use .data when:

  • You need to store additional information about an element that isn’t part of the HTML attributes.
  • You want to cache complex data types like objects or arrays.
  • You need to retrieve data attributes efficiently.

Example: Storing and retrieving complex data

$("#user").data("info", { company: "Intellipaat", course: web development });

console.log($("#user").data("info").company);

Real-world Examples of .attr() and .data().

Understanding real-world scenarios makes it easier to decide when to use attr or data in jQuery. Here are a few simple examples that show how both methods work in practical situations.

1. Updating an Image Source: jQuery .attr() Example

You should use .attr() when you need to change or read actual HTML attributes.

Here’s a quick jQuery .attr() example:

// Change image source on button click

$("#updateBanner").click(function() {

    $("#bannerImg").attr("src", "new-banner.jpg");

});

2. Storing Extra Information for UI Logic – jQuery .data() Example

Use .data() when you want to store temporary or dynamic information without modifying the HTML markup.

Here’s a jQuery .data() example:

// Store data about a product

$("#productCard").data("details", {

    name: "Laptop",

    price: 55000

});

// Retrieve it later

console.log($("#productCard").data("details").price);

Use Case:

Storing objects, states, or values that don’t belong as HTML attributes, like pricing, user selections, or temporary state values.

3. Passing Data to Click Handlers

When handling events, .data() is useful for passing information without embedding it in the HTML.

$(".btn").each(function(index) {

    $(this).data("order", index + 1);

});

$(".btn").click(function() {

    alert("Button number: " + $(this).data("order"));

});

Use Case:

Numbering elements, storing metadata, or adding context to event listeners.

<div id="conclusion"></div>

Conclusion

You can use .attr() to get or set an element’s attributes and .data() to save and access data tied to an element. Understanding their differences will give you a better understanding of where and how to use them.

 

Dive into the basics of JavaScript programming with the detailed articles listed below.-

Include Another Html File In A Html File – Find out how to insert an HTML file into another HTML file in this blog.

How To Change The Css Background Opacity Of An Element – Explore techniques for setting background opacity on elements via CSS in this blog.

Retrieve The Position Xy Of An Element Using Html – Find out how to implement retrieval of element position coordinates using HTML in this blog.

How To Change Input Typedate Format In Html – Explore methods to alter the date input format in HTML in this blog.

Lateral Join Vs Subqueries In Postgresql – Find out how to apply lateral joins and subqueries effectively in PostgreSQL in this blog.

Css Text Align To Horizontally Center Element – Find out how to achieve horizontal centering of elements with CSS text-align in this blog.

How To Make An Element Width 100 Minus Padding – Here, you’ll learn how to set an element’s width minus padding to 100% in this blog.

Css Selectors And Specificity – Explore how to apply CSS selectors and handle specificity in this blog.

Why Dont Self Closing Script Elements Work – Here, we explain the reasons self-closing script elements don’t behave correctly in this blog.

jQuery Data vs Attr – FAQs

1. What’s the difference between .data() and .attr()?

You can use .data() to store and access custom data and .attr() to get and set attributes.

2. Can .data() work with HTML attributes like data-*?

Yes, you can use .data() to get the data from data-* attributes in the HTML.

3. When should I use .data() instead of .attr()?

If you do not need data to be visible in the HTML element, you can use .data().

4. Does .data() persist the data in the DOM?

No, the data that gets stored in the using .data() is handled internally by jQuery.   

5. Are .data() values accessible by non-jQuery methods?

Data stored using .data() isn’t directly accessible through JavaScript methods.

About the Author

Software Developer | Technical Research Analyst Lead | Full Stack & Cloud Systems

Ayaan Alam is a skilled Software Developer and Technical Research Analyst Lead with 2 years of professional experience in Java, Python, and C++. With expertise in full-stack development, system design, and cloud computing, he consistently delivers high-quality, scalable solutions. Known for producing accurate and insightful technical content, Ayaan contributes valuable knowledge to the developer community.

Full Stack Developer Course Banner