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 elementfunction$(selector, parent = document){returnparent.querySelector(selector);}/* -------- helper -------- */// โญ๏ธ string.capitalize()String.prototype.capitalize=function() {returnthis.charAt(0).toUpperCase() +this.slice(1);};// โญ๏ธ string.kebabToCamelCase()// kebab case | camel case// aaa-bbb-ccc | aaaBbbCccString.prototype.kebabToCamelCase=function() {returnthis.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(){ returnthis// '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 & propertyElement.prototype.showDataAttr=function (dataAttr){constprop=dataAttr.toDatasetPropName();log(`${this.nodeName.toLowerCase()}.${prop} = '${this.dataset[prop]}'`);log(`${dataAttr}='${this.attr(dataAttr)}'`);}/* -------- โญ๏ธ data-xxx attribute -------- */constdiv=$('[data-widget-name]');div.showDataAttr('data-widget-name');// div.widgetName = 'menu'// data-widget-name='menu'