Tutorialspoint.dev

jQuery | data() with Examples

The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements.
Syntax:

$(selector).data(para1);

Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element.
Return Value: It returns the retrieved data for the selected element.

jQuery code to show the working of data() method:

Code #1:
In the below code, data is attach to the selected element.

<html>
  
<head>
                 jquery/3.3.1/jquery.min.js"></script>
    <style>
        div {
            display: block;
            width: 500px;
            font-size: 37px;
            padding: 50px;
            background-color: lightgrey;
        }
          
        span {
            color: green;
        }
    </style>
</head>
  
<body>
    <div>
        Welcome to
        <span></span>for<span></span>!
    </div>
    <script>
        <!-- jQuery code to perform data method -->
        $("div").data("test", {
            first: "Geeks",
            last: "Geeks !"
        });
        $("span:first").text($("div").data("test").first);
        $("span:last").text($("div").data("test").last);
    </script>
</body>
  
</html>

Output:

Code #2:
In the below code, The data is attaching and retrieving from the “div” element using buttons.

br>
<html>
  
<head>
                 jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
        <!--Here data is attaching to the div element -->
            $("#b1").click(function() {
                $("div").data("g", "GeeksforGeeks !!!");
            });
        <!-- Here data is retriving from the div elemment -->
            $("#b2").click(function() {
                alert($("div").data("g"));
            });
        });
    </script>
    <style>
        #b1,
        #b2 {
            padding: 10px;
            margin: 5px;
        }
    </style>
</head>
  
<body>
<!-- This button will attach data to the div element -->
    <button id="b1">This will attach data to div
                       element</button>
    <br>
<!-- This button retrieve the attached data
            from the div element -->
    <button id="b2">This will retrieve the attached data
                     to div element</button>
    <div></div>
</body>
  
</html>

Output:
Just after clicking the run button-

After clicking the “This will retrieve the attached data to div element” button just after clicking the “This will attach data to div element” button-

After clicking the “This will retrieve the attached data to div element” button without clicking the “This will attach data to div element” button-



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter