How to store data to DOM ?
In this article, we will learn how to store data in 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 on 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:
- Any Data stored in a DOM can be viewed in the source code(Developer Tool).
- You cannot use uppercase with data-* attributes
Example 1: In this example, we will use data-* attribute to store data.
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) {
let discount =
book.getAttribute("data-discount");
alert(discount);
}
</ script >
</ body >
</ html >
|
Output:
You can also use data() method in jQuery to store Data on DOM which is an inbuilt method in jQuery that is used to attach data or get data for the selected elements.
Syntax:
$(selector).data(para1);
Example 2: In this example, we will use the data() method.
HTML
< html >
< head >
< script src =
</ 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 >
//
$("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:
Last Updated :
17 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...