Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • jQuery Tutorial
  • jQuery Selectors
  • jQuery Events
  • jQuery Effects
  • jQuery Traversing
  • jQuery HTML & CSS
  • jQuery AJAX
  • jQuery Properties
  • jQuery Examples
  • jQuery Interview Questions
  • jQuery Plugins
  • jQuery Cheat Sheet
  • jQuery UI
  • jQuery Mobile
  • jQWidgets
  • Easy UI
  • Web Technology
Open In App
Next Article:
jQuery | removeData() with Examples
Next article icon

jQuery | data() with Examples

Last Updated : 27 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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




<html>
 
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/
                 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. 

html




<html>
 
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/
                 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 retrieving from the div element -->
            $("#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- 
 

 



Next Article
jQuery | removeData() with Examples

K

kundankumarjha
Improve
Article Tags :
  • JavaScript
  • JQuery
  • Web Technologies
  • jQuery-Misc

Similar Reads

  • jQuery serialize() with Examples
    The serialize() method is an inbuilt method in jQuery that is used to create a text string in standard URL-encoded notation. This method can act on a jQuery object that has selected individual form controls, such as input, textarea etc. Syntax: $(selector).serialize()Parameters: This method does not
    1 min read
  • jQuery | removeData() with Examples
    The removeData() is an inbuilt method in jQuery that is used to remove those data which are previously set with the data() method. Syntax:$(selector).removeData(args); Here "selector" is the selected element whose previously set data gets removed. Parameter: It accepts an optional parameter "args" w
    1 min read
  • jQuery serializeArray() with Examples
    The serializeArray() is an inbuilt method in jQuery that is used to create a JavaScript array of objects that is ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls. The controls can be of several types. JSON string is a text and can convert any Jav
    1 min read
  • JavaScript Array Examples
    JavaScript array is used to store multiple elements in a single variable. [GFGTABS] JavaScript let a = ["HTML", "CSS", "JS"] console.log(a) [/GFGTABS]Output[ 'HTML', 'CSS', 'JS' ] Using New Keyword [GFGTABS] JavaScript // Declaring an array using Array Constructor let a
    3 min read
  • jQuery event.data Property
    jQuery event.data property is used to contain the optional data which is passed to an event method. The data is passed when the currently executing handler is bound.  Syntax:event.dataParameters:event: It is the parameter that is used to specify the name of the event type on the selector.Example 1:
    2 min read
  • jQuery $.ajaxPrefilter() Method
    Jquery $.ajaxPrefilter() method is a powerful jquery method that allows us to modify the settings, option object, URL, and data object of AJAX jquery request before sending a request to the server. If you know the syntax of the AJAX jquery request, you will find that it contains options, objects, an
    4 min read
  • JQuery hasData() method
    This hasData() method in JQuery is used to determine whether an element has any jQuery data associated with it. This data may be text, event associated with element. There are two examples discussed below: Syntax: jQuery.hasData(element)Arguments: element: This parameter is a DOM element which is to
    2 min read
  • jQuery ajax() Method
    The jQuery ajax() method is used to perform asynchronous HTTP requests, allowing you to load data from a server without reloading the webpage. It provides a flexible way to interact with remote servers using GET, POST, or other HTTP methods, supporting various data formats. Syntax:$.ajax({name:value
    4 min read
  • jQuery ajaxSetup() Method
    The ajaxSetup() method in jQuery is used to set the default values for future AJAX requests. Syntax: $.ajaxSetup( {name:value, name:value, ... } )Parameters: type: It is used to specify the type of request.url: It is used to specify the URL to send the request to.username: It is used to specify a us
    3 min read
  • How to use array with jQuery ?
    An array is a linear data structure. In JavaScript, arrays are mutable lists with a few built-in methods, we can define arrays using the array literal. The arrays can be used in the same way in jQuery as used in JavaScript. Syntax And Declaration:let arr1=[];let arr2=[1,2,3];let arr2=["India","usa",
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences