🔰data attributes

🔰 HTMLHTML 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