Javascript examples for jQuery Method and Property:data
The data() method attaches data to, or gets data from, selected elements.
$(selector).data(name);
Parameter | Require | Description |
---|---|---|
name | Optional. | name of data to retrieve. |
$(selector).data(name,value);
Parameter | Require | Description |
---|---|---|
name | Required. | name of data to set |
value | Required. | value of data to set |
$(selector).data(object)
Parameter | Description |
---|---|
object | Required. Specifies an object containing name/value pairs |
If no name is specified, this method returns all stored data for the element as an object
The following code shows how to Attach data to a <div> element, then retrieve the data:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("div").data("greeting", "Hello World"); });/* w ww .j a va 2 s . c o m*/ $("#btn2").click(function(){ console.log($("div").data("greeting")); }); }); </script> </head> <body> <button id="btn1">Attach data</button><br> <button id="btn2">Get data attached</button> <div></div> </body> </html>