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:
- name: It specifies the name of an element
- style: It is used to beautify an element
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:
- key: A string naming the piece of data to get.
Return:
- It returns the value at the named data store for the first element in the set of matched elements.
Approach:
- Consider mydata is the name of your custom attribute. In the HTML element, write it as data-mydata and store some data in it.
<h1 id="someid" data-mydata ="THIS IS CUSTOM ATTRIBUTE DATA"></h1>
- Now pass the name of the attribute to the data() method to get the custom attribute data.
$('#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:
- key: The name of the attribute to get.
Return:
- It returns the value at the named data store for the first element in the set of matched elements.
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: