1.0.0 • Published 1 year ago

@phucbm/get-options-from-html-attr v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

@phucbm/get-options-from-html-attr

Test Status NPM Publish NPM Version

A utility function to parse options from a specified attribute of a target element, with support for default values, numeric conversion, and JSON validation.

Installation

First, ensure you have Node.js and npm installed. Then, install the package using npm:

npm i @phucbm/get-options-from-html-attr

Usage

Importing the Function

import { getOptionsFromAttribute } from '@phucbm/get-options-from-html-attr';

Function Parameters

The getOptionsFromAttribute function accepts an object with the following properties:

ParameterTypeDefault ValueDescription
targetHTMLElementnullnullThe target HTML element.
attributeNamestring''The name of the attribute to parse.
defaultOptionsRecord<string, any>{}The default options to return if parsing fails.
numericValuesstring[][]An array of property names to convert to float.
onIsString(data: string) => voidundefinedA callback function to execute if value is not JSON.
devbooleanfalseEnable or disable development mode.

Example Usage

import { getOptionsFromAttribute } from '@phucbm/get-options-from-html-attr';

const targetElement = document.getElementById('example-element');

const options = getOptionsFromAttribute({
  target: targetElement,
  attributeName: 'data-options',
  defaultOptions: { key: 'defaultValue' },
  numericValues: ['numericValue'],
  onIsString: (data) => { console.log('Not a JSON string:', data); },
  dev: true,
});

console.log(options);

Example HTML

<div id="example-element" data-options='{"key":"value", "numericValue":"123.45", "isTrue":"true", "isFalse":"false"}'></div>

Expected Output

When the above HTML and JavaScript are used, the options object will be:

{
  key: 'value',
  numericValue: 123.45,
  isTrue: true,
  isFalse: false
}

Testing

npx jest

Ensure all tests pass.

License

This project is licensed under the MIT License.


1.0.0

1 year ago