HTML - Data attributes

> (World Wide) Web - (W3|WWW) > HyperText markup Language (HTML)

1 - About

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

Advertising

3 - Example

3.1 - Css

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

3.2 - Dom Select

<article
  id="electriccars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>
var article = document.getElementById('electriccars');
article.dataset.columns // "3"
article.dataset.indexNumber // "12314"
article.dataset.parent // "cars"

3.3 - Event

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')
    }
})
<div data-echo="nico">Click Me to Hello Nico</div>
<div >Click Me to see that there is no data attribute</div>

4 - Documentation / Reference

Advertising
web/html/data_attribute.txt · Last modified: 2019/03/12 10:12 by gerardnico