๐Ÿ”ฐdata attributes

๐Ÿ”ฐ HTML โŸฉ HTML Attributes โŸฉ

Custom Attributes

Problem with custom attributes: What if we use a non-standard attribute and later the standard introduces it and makes it do something? ... To avoid conflicts, there exist data-* attributes.

dataset

All attributes starting with โ€œdata-โ€ are reserved for programmersโ€™ use. They are available in the dataset property.

data-xxx attribute (โญ๏ธ kebab-cased)

dataset property (โญ๏ธ camel-cased)

data-about="Elephants"

dataset.about = "Elephants"

data-order-state="new"

dataset.orderState = "new"

const {log} = console;

/* -------- selector -------- */

// โญ๏ธ $(): select first element
function $(selector, parent = document){
  return parent.querySelector(selector);
}

/* -------- helper -------- */

// โญ๏ธ string.capitalize()
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

// โญ๏ธ string.kebabToCamelCase()
// kebab case  | camel case
// aaa-bbb-ccc | aaaBbbCcc
String.prototype.kebabToCamelCase = function() {
    return this
      .split('-')
      .map((str, i) => (i === 0 ? str : str.capitalize()) )
      .join('');
};

// โญ๏ธ string.toDatasetPropName()
//    string is assumed to be in "data-xxx" format (kebab case)
String.prototype.toDatasetPropName = function(){                     
    return this                       // 'data-xx-yy-zz'
      .split('-')                     // ['data', 'xx', 'yy', 'zz']
      .slice(1)                       // remove 'data'
      .map((str, i) => (i === 0 ? str : str.capitalize()) ) // ['xx', 'Yy', 'Zz']
      .join('');                      // xxYyZz
};

// โญ๏ธ elem.showDataAttr('')
// show element's "data-xxx" attribute & property
Element.prototype.showDataAttr = function (dataAttr){
  const prop = dataAttr.toDatasetPropName();
  log(`${this.nodeName.toLowerCase()}.${prop} = '${this.dataset[prop]}'`);
  log(`${dataAttr}='${this.attr(dataAttr)}'`);
}

/* -------- โญ๏ธ data-xxx attribute -------- */

const div = $('[data-widget-name]');
div.showDataAttr('data-widget-name');
// div.widgetName = 'menu'
// data-widget-name='menu'

Last updated