Skip to content
Related Articles

Related Articles

Improve Article

How to store data to DOM ?

  • Last Updated : 22 Jun, 2021

In this article we will learn how to store data to DOM. You can use data-* attribute to store data or information on DOM. The data-* attributes can be used to define our own custom data attributes. It is used to store custom data in private to the page or application.

There are mainly 2 parts of the Data Attributes:

  • Attribute Name: The attribute name should be at least one character long, contain no capital letters and be prefixed with ‘data-‘.
  • Attribute Value: Can be any string.

Syntax:

<div data-row = "value" data-column = "value"
     data-index = "value">
</div>

Note:

  1. Any Data stored in a DOM can be viewed in the source code(Developer Tool).
  2. You cannot use uppercase with data-* attributes

Example 1:



HTML




<!DOCTYPE html>
 
<body>
  <div>
    <h4>Data Structure And Algorithm</h4>
    <button onclick="showDetails(this)" id="one"
        data-discount="60%">Click Here for Discount
    </button>
  </div>
  <br>
 
  <div>
    <h4>Operating System</h4>
    <button onclick="showDetails(this)" id="one"
        data-discount="60%">Click Here for Discount
    </button>
  </div>
  <br>
 
  <div>
    <h4>Competitive Programming</h4>
    <button onclick="showDetails(this)" id="one"
        data-discount="60%">Click Here for Discount
    </button>
  </div>
 
  <script>
    function showDetails(book) {
      var discount =
        book.getAttribute("data-discount");
        alert(discount);
    }
  </script>
</body>
 
</html>

Output:

Example 2:

You can also use data() method in jQuery to store Data on DOM which is an inbuilt method in jQuery which is used to attach data or get data for the selected elements.

Syntax:

$(selector).data(para1);

HTML




<html>
 
<head>
      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>
    Course Includes
    <span></span> and <span></span>!
  </div>
 
  <script>
    // <!-- jQuery code to perform data method -->
    $("div").data("test", {
        first: "Operative System",
        last: "Competitive Programming"
    });
    $("span:first").text($("div").data("test").first);
    $("span:last").text($("div").data("test").last);
  </script>
</body>
 
</html>

Output:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :