data-settings
v0.1.1
Published
Get data from data-attributes
Downloads
7
Readme
data-settings
Getting data from data-attributes in DOM
Install
npm install data-settings
Usage
Simple get data:
<div class="component" data-component='{"format": "Y-m-d"}'></div>
import dataSettings from 'data-settings';
let element = document.querySelector('.component');
let data = dataSettings(element, 'component'); // { format: 'Y-m-d' }
Path in namespace:
<div class="component" data-component='{"value": 10, "subComponent": {"format": "Y-m-d"}}'></div>
import dataSettings from 'data-settings';
let element = document.querySelector('.component');
let data = dataSettings(element, 'component.subComponent'); // { format: 'Y-m-d' }
Shorthands usage:
<div class="component" data-component='{"value": 10}' data-component-format="Y-m-d" rel="group"></div>
import dataSettings from 'data-settings';
let element = document.querySelector('.component');
let data = dataSettings(element, 'component', null, {
format: 'format',
'@rel': 'group',
});
// { value: 10, format: 'Y-m-d', group: 'group' }
Strict mode:
<div class="component" data-component="test"></div>
import dataSettings from 'data-settings';
let element = document.querySelector('.component');
let data1 = dataSettings(element, 'component'); // 'test'
let data2 = dataSettings(element, 'component', null, null, true); // throw Error
Documentation
dataSettings(element, namespace[, defaultValue[, shorthands[, strict]]])
element {HTMLElement}
- DOM elementnamespace {string}
- namespacedefaultValue {*} [undefinded]
- value if data is not foundshorthands {Object} [undefinded]
- shorthands liststrict {boolean} [false]
- enable strict mode
Testing
To run tests, use:
npm test
If necessary, you can install launchers for other browsers and activate them in karma.conf.js
:
npm i --save-dev karma-ie-launcher
Browser support
- Internet Explorer 11+
- Other modern browsers