jQuery Data vs Attr

jQuery Data vs Attr

The popular methods in jQuery are .data() and .attr(). You can store and retrieve the values in the DOM element by these methods. In this blog, we will discuss their differences with examples.

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()

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);

Conclusion

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

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

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner