HTML - Data attributes

About

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

Example

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.

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

Dom Manipulation

  • 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("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:

Add/Remove

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

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