HTML data attribute

HTML data attribute

The HTML data global attribute, introduced in HTML 5, is used to embed custom data to the HTML elements. The custom data specified in this attribute is private to the page or application and it can be accessed by JavaScript or CSS.

<p data-exp="Hypertext Markup Language">HTML</p>

Things to remember

  • The name should not contain any uppercase letters.
  • The name must not contain any semicolon .
  • The name should be at least one character long.

Accessing data with JavaScript

Data specified in the data-* attribute can be retrieved using any of the following methods.

1) Using dataset property

<p data-id="0001" onclick="msConfirmDelete(this)">Click to delete item 1</p>
<p data-id="0002" onclick="msConfirmDelete(this)">Click to delete item 2</p>
<p data-id="0003" onclick="msConfirmDelete(this)">Click to delete item 3</p>  
<p id="msMessage" style="color:red"></p>
<script>
function msConfirmDelete(msElement)
{
   var msDelId=msElement.dataset.id;
   document.getElementById('msMessage').innerHTML="Selected item with id: "+msDelId+" will be deleted";
}
</script> 

The above program when executed will produce the following output:

Click on the elements to view output.

Click to delete item 1

Click to delete item 2

Click to delete item 3

2) Using getAttribute() method

<p data-id="0001" onclick="msConfirmDelete(this)">Click to delete item 1</p>
<p data-id="0002" onclick="msConfirmDelete(this)">Click to delete item 2</p>
<p data-id="0003" onclick="msConfirmDelete(this)">Click to delete item 3</p>  
<p id="msMessage" style="color:red"></p>

<script>
function msConfirmDelete(msElement)
{
   var msDelId=msElement.getAttribute("data-id");
   document.getElementById('msMessage').innerHTML="Selected item with id: "+msDelId+" will be deleted";
}
</script>

The above program when executed will produce the following output:

Click on the elements to view output.

See the Pen WLVjzb by Mishel Shaji (@mishelshaji) on CodePen.


Share Tweet Send
Loading...
You've successfully subscribed to Geekinsta
Great! Next, complete checkout for full access to Geekinsta
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.