https://github.com/gsantiago/extract-data-options
Extract `data-(namespace)-*` options from a HTML element
https://github.com/gsantiago/extract-data-options
attributes data element extract html options
Last synced: about 1 year ago
JSON representation
Extract `data-(namespace)-*` options from a HTML element
- Host: GitHub
- URL: https://github.com/gsantiago/extract-data-options
- Owner: gsantiago
- License: mit
- Created: 2017-02-26T23:09:31.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2017-02-26T23:24:29.000Z (over 9 years ago)
- Last Synced: 2025-04-07T02:37:21.303Z (about 1 year ago)
- Topics: attributes, data, element, extract, html, options
- Language: JavaScript
- Homepage:
- Size: 7.81 KB
- Stars: 5
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# extract-data-options
[](https://travis-ci.org/gsantiago/extract-data-options)
[](https://saucelabs.com/beta/builds/7e2581ea500d489a9d2e434435c5e72c)
[](https://badge.fury.io/js/extract-data-options)
[](http://standardjs.com/)
Extract options from data attributes:
```html
```
```js
// Import the module
var extractDataOptions = require('extract-data-options')
// Get the element
var element = document.querySelector('.js-carousel')
// Extract the options from `data-carousel-*` attributes
var options = extractDataOptions(element, 'carousel')
```
The function will return:
```js
{
index: 0,
autoPlay: true,
controls: {
prev: '.js-prev',
next: '.js-next'
},
dots: '.my-dots'
}
```
## installation
`npm install extract-data-options --save`
## usage
### function
`extractDataOptions(element: HTMLElement, namespace: String) : Object`
If you don't pass a namespace, it will return all data-* options.
### camel case
This module will automatically convert the attributes names into camelCase. So, an attribute like `data-example-my-option` will be turned into `myOption`.
### nested properties
You can use nested properties too. Just use a dot (`.`) to define the keypath:
`data-example-prop.show.example="hello"`, will result into:
```js
{
prop: {
show: {
example: 'hello'
}
}
}
```
**OBS:** Don't worry about this notation with dots. It is a [valid HTML5 standard](https://www.w3.org/TR/html/syntax.html#elements-attributes).
### json
This module will always attempt to parse the values as JSON, otherwise it will set the value as a String.
The following options:
```html
```
Will produce the result below:
```js
{
boolean: true,
number: 3.14,
object: {key: 'value'},
array: [1, 2, 3],
string: 'A simple string'
}
```
## tests
Install all dependencies:
`npm install`
Run the tests:
`npm test`
## license
MIT