How to Get the data-id Attribute

jQuery provides multiple methods for manipulating the HTML elements. In this tutorial, you will learn two simple and fast ways of getting data-id.

Assuming you have the following link:

<a data-id="457">link</a>

The attr() Method

To get the content of the data-id attribute use the attr() method, which will return a string:

$(this).attr("data-id") // returns the string "457"
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style>
      div p {
        display: inline-block;
        margin: 10px;
        list-style: none;
        opacity: 0.8;
      }
      div p:hover {
        opacity: 1;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  </head>
  <body>
    <div class="divClass">
      <p data-id="id1">
        <a href="#"> Link1</a>
      </p>
      <p data-id="id2">
        <a href="#"> Link2</a>
      </p>
      <p data-id="id3">
        <a href="#"> Link3</a>
      </p>
    </div>
    <script>
      $(document).ready(function() {
          $(".divClass p").on("click", function() {
              let dataId = $(this).attr("data-id");
              alert("The data-id of clicked item is: " + dataId);
            });
        });
    </script>
  </body>
</html>

The data() Method

In case of jQuery >= 1.4.3 version, you can use the data() method:

$(this).data("id") // returns the number 567
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style>
      div p {
        display: inline-block;
        margin: 10px;
        list-style: none;
        opacity: 0.8;
      }
      div p:hover {
        opacity: 1;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  </head>
  <body>
    <div class="divClass">
      <p data-id="id1">
        <a href="#"> Link1</a>
      </p>
      <p data-id="id2">
        <a href="#"> Link2</a>
      </p>
      <p data-id="id3">
        <a href="#"> Link3</a>
      </p>
    </div>
    <script>
      $(document).ready(function() {
          $(".divClass p").on("click", function() {
              let dataId = $(this).data("id");
              alert("The data-id of clicked item is: " + dataId);
            });
        });
    </script>
  </body>
</html>
Make sure your attribute contains only lowercase letters, for example, data-idNum won’t work, but data-idnum will.

The attr() and data() Methods

The .data() method allows attaching data of any type to DOM elements in a safe way from circular references and memory leaks. The data() method used for updating data does not affect attributes in the DOM. To set the data-* attribute value, you can use the attr method. It will get the attribute value for only the first element in the matched set.

Using jQuery 1.6, the .attr() method will return undefined for attributes that have not been set.