HTML - Data attributes

About

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

Example

Css

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

where attr is the css attribute function

  • Output:

Dom Select

  • Code:
<article
  id="electriccars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
</article>
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("Index number: "+article.dataset.indexNumber); // "12314"
console.log("Parent: "+article.dataset.parent); // "cars"
  • Output:

Event

  • 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 (event.target.dataset.echo) {
        console.log('The target element has a data-echo attribute. Hello '+event.target.dataset.echo+' !')
    } 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