DEV Community

bryancasler
bryancasler

Posted on

TIL: Data Attributes are way easier to use than I realized

Today I learned about how "dataset" can be leveraged in Javascript to quickly retrieve a data attribute on an object. Per the MSDN docs, note that dashes are converted to camelCase.

And this approach has 99%+ support in browsers.

<article
  id="electric-cars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>

<script>
const article = document.querySelector('#electric-cars');

article.dataset.columns // "3"
article.dataset.indexNumber // "12314"
article.dataset.parent // "cars"
</script>

REF: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

Top comments (0)