
- jQuery - Home
- jQuery - Roadmap
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
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