data() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:data

Description

The data() method attaches data to, or gets data from, selected elements.

Syntax to get data

$(selector).data(name);
Parameter Require Description
name Optional.name of data to retrieve.

Syntax to set data

$(selector).data(name,value);
Parameter Require Description
name Required.name of data to set
value Required.value of data to set

Attach Data to an Element Using an Object

$(selector).data(object)
Parameter Description
objectRequired. 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:

Demo Code

ResultView the demo in separate window

<!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>

Related Tutorials