Using data-attributes (via JS, CSS)

Example of using data-attributes on HTML Elements and how we can use them in CSS and access them in JS

by Konstantin Rouda

HTML

<p>
  <a href="some-cool-file.pdf" data-size="35kb" id="anchor">download</a>
</p>

CSS

/*
  1. Fallback for the browsers that don't support `fit-content`
*/
P {
  max-width: 200px; /*[1]*/
  text-align: center; /*[1]*/
  max-width: fit-content;
  margin: 5rem auto;	
}

/*
  1. Display file extension, if <a> (achor element) only has href without `data-size` attribute
*/
[href$=pdf]::after {
  content: " (PDF)"; /*[1]*/
}

/*
  1. Display file extension and file size if <a> (anchor element) has attribute `data-size`.
  NOTE: this property will override the property above
*/
[href$=pdf][data-size]::after {
  content: " (PDF) (size: " attr(data-size) ")"; /*[1]*/
}

JavaScript

;(function () {
	"use strict";
  
  /*
   Example of getting data attribute value via JS
  */
  
  const anchorElem =  document.getElementById("anchor");
  
  // in Browsers that support dataset
  let fileSize = anchorElem.dataset.size;
  
  // in Browsers that don't support dataset
  fileSize = anchorElem.getAttribute("data-size");
  debugger;
  
})();


/*
MDN link:

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

*/