HTML - Data attributes


Data (Key value) can be included for processing by a script using the data-*=“” attributes.


How to use data attribute in Css property value

<p data-length="2m" >Beyond The Sea</p>
p::before {
   content: attr(data-length) " ";

where attr is the css attribute function

  • Output:

Dom Select

With an attribute selector, you can select the nodes with a certain value.

  <li data-type="blue">Blue</li>
  <li data-type="red">Red</li>
*[data-type="blue"] {
   color: blue;
  • Output:

Dom Manipulation

  • Code:
var article = document.getElementById('electriccars');
console.log("Columns: "+article.dataset.columns); // "3"
console.log("Has Columns As Property ?: "+article.dataset.hasOwnProperty("columns")); // true
console.log("Has Columns As Property With In operator ?: "+("columns" in article.dataset)); // true
console.log("Index number: "+article.dataset.indexNumber); // "12314"
console.log("Parent: "+article.dataset.parent); // "cars"
  • Output:


As this is a normal attribute, you add or remove it via the standard DOM attribute manipulation function.

Is set

  • the in operator can check if a data attribute is present
'keyname' in element.dataset


  • Javascript that check on each element clicked in the body if there is a data attribute (ie data-echo) and log it's result to the console.
document.body.addEventListener('click', (event) => {
    if ( {
        console.log('The target element has a data-echo attribute. Hello '' !')
    } else {
       console.log('The target element has NOT a data-echo attribute')
  • The two buttons to click
<p><button data-echo="you">Click Me ! (To see that there is a data attribute, that output the `you` value)</button></p>
<p><button>Click Me ! (To see that there is no data attribute on this button)</button></p>
  • Output:

Documentation / Reference

Powered by ComboStrap