Open In App

How to get custom element attribute data in jQuery ?

Apart from attributes, we can also use custom element attributes. In this article, we will learn how to get the value of a custom attribute in an HTML element using jQuery.

What is Attribute? The HTML attribute provides information about the element. It decides the behavior of an element.



Examples of attributes:

Custom element attribute: Custom element attributes can be used to embed custom data about the element in a (key, value) format. They can be used to store data privately on a specific page. 



Using data(): The data() method in jQuery can be used to get the data of custom attributes that start with data-.

Syntax:

.data( key )

Parameters:

Return:

Approach:

<h1 id="someid" data-mydata ="THIS IS CUSTOM ATTRIBUTE DATA"></h1>
$('#someid').data('mydata')

Example 1: We will see the full code of how to use custom element attributes and how to get the data of custom attributes in jQuery.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <script>
        function getCustomAttributeData(attName){
            $(document).ready(function() {
               alert($('#someid').data(attName));
            });
        }         
    </script>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h1 id="someid" data-mydata="THIS IS CUSTOM ATTRIBUTE DATA">
    </h1>
    Click to display custom attribute data :
    <button onclick="getCustomAttributeData('mydata')">
        Click
    </button>
</body>
  
</html>

Output:

 

Using .attr(): The attr() method in jQuery can be used to get the data of custom attributes.

Syntax:

.attr( key )

Parameters:

Return:

Approach:

1. Consider mydata is the name of your custom attribute. In the HTML element assign some data to mydata attribute.

<h1 id="someid" mydata ="THIS IS CUSTOM ATTRIBUTE DATA"></h1>

2. Now pass the name of the attribute to the attr() method to get the custom attribute data.

$('#someid').attr('mydata')

Example 2:




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <script>
        function getCustomAttributeData(attName){
             $(document).ready(function() {
               alert($('#someid').attr(attName));
             });
        }         
    </script>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h1 id="someid" mydata="THIS IS CUSTOM ATTRIBUTE DATA">
    </h1>
    Click to display custom attribute data :
    <button onclick="getCustomAttributeData('mydata')">
        Click
    </button>
</body>
  
</html>

Output:

 


Article Tags :