• jQuery Video Tutorials

jQuery Misc data() Method



The data() method in jQuery is used to attach data to, or to retrieve the data from the selected elements.

Syntax

Following is the syntax of this method to "return data from an element"

$(selector).data(name)

Parameters

Here is the description of the above syntax −

  • name: A string representing the name of the data attribute you want to retrieve.

Following is the syntax of this method to "attach data to an element"

$(selector).data(name, value)

Parameters

Here is the description of the above syntax −

  • name: A string representing the name of the data attribute you want to set.
  • value: The value you want to assign to the data attribute.

Example

In the following example, we are using the "jQuery Misc data() method" to attach data to a <div> element, then retrieve the data −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Attach data when the button is clicked
            $("#attachData").click(function(){
                $("div").data("role", "page");
                $("div").data("userId", 42);
                $("div").data("theme", "dark");
                alert("Data attached!");
            });

            // Retrieve and display data when the button is clicked
            $("#retrieveData").click(function(){
                var role = $("div").data("role");
                var userId = $("div").data("userId");
                var theme = $("div").data("theme");

                document.write("Role: " + role + "<br>");
                document.write("User ID: " + userId + "<br>");
                document.write("Theme: " + theme + "<br>");
            });
        });
    </script>
</head>
<body>
    <div>
        This is a div element with data attributes.
    </div>
    <button id="attachData">Attach Data</button>
    <button id="retrieveData">Retrieve Data</button>
</body>
</html>

Execute and click the buttons to attach data to a <div> and retrieve the data.

jquery_ref_miscellaneous.htm
Advertisements