An open API service indexing awesome lists of open source software.

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

Awesome Lists containing this project

README

          

# extract-data-options
[![Build Status](https://travis-ci.org/gsantiago/extract-data-options.svg?branch=master)](https://travis-ci.org/gsantiago/extract-data-options)
[![Build Status](https://saucelabs.com/buildstatus/extactdataoptions)](https://saucelabs.com/beta/builds/7e2581ea500d489a9d2e434435c5e72c)
[![npm version](https://badge.fury.io/js/extract-data-options.svg)](https://badge.fury.io/js/extract-data-options)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)



Sauce Test Status

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