jQuery data() with Examples


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

Syntax

The syntax is as follows −

$(selector).data(name)
$(selector).data(name,value)

Above, the name is the name of data to retrieve for the 1st syntax.

For the 2nd syntax, the name is the name of data to set, whereas value is the value of data to set.

Example

Let us now see an example to implement the jQuery data() method 

 Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $(".button1").click(function(){
         $("div").data("student", "Jack Sparrow");
         alert("Student Name = " +$("div").data("student"));
      });
      $(".button2").click(function(){
         $("div").removeData("student");
         alert("Student Name = " +$("div").data("Jack Sparrow"));
      });
   });
</script>
<style>
.button1 {
   background-color: orange;
   color: white;
}
.button2 {
   background-color: orange;
   color: white;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<button class="button1">Attach</button><br><br>
<button class="button2">Remove</button>
<div></div>
</body>
</html>

Output

This will produce the following output −

Updated on: 31-Dec-2019

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements