jQuery data()

Introduction

Attach data to a <div> element, then retrieve the data:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/*w w w  .j  av a 2 s  . c om*/
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("div").data("greeting", "Hello World");
  });
  $("#btn2").click(function(){
    document.getElementById("demo").innerHTML = $("div").data("greeting");
  });
});
</script>
</head>
<body>

<p id="demo"></p>
<button id="btn1">Attach data to div element</button><br>
<button id="btn2">Get data attached to div element</button>

<div></div>

</body>
</html>

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

To remove data, use the removeData() method.

Returns attached data from a selected element.

$(selector).data(name)
Parameter
Optional
Description
name

Optional.

name of data to retrieve.
If no name is specified, it returns all stored data as an object

Attach data to selected elements.

$(selector).data(name,value)
Parameter OptionalDescription
name Required. the name of data to set
value Required. the value of data to set

Attach Data to an Element Using an Object

Attach data to selected elements using an object with name/value pairs.

$(selector).data(object)
Parameter OptionalDescription
objectRequired. an object containing name/value pairs



PreviousNext

Related