2.0.2 • Published 9 months ago

@frankhoodbs/data-attributes-utils v2.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
9 months ago

Data Attributes Utils

A simple JavaScript utility to fetch and parse data attributes from HTML elements. Perfect for modern web development, this utility helps you easily extract custom data attributes and converts them to their respective JavaScript types where possible.

Version License

Installation

Via NPM:

npm install @frankhoodbs/data-attributes-utils

Usage

Here's a basic example on how to use the getDataAttributes utility:

import { getDataAttributes } from '@frankhoodbs/data-attributes-utils';

const element = document.querySelector('.your-element-class');

const dataAttributes = getDataAttributes(element);
console.log(dataAttributes);

The function will retrieve all data attributes from the provided HTML element and return them as a parsed JavaScript object. If a data attribute contains a stringified JSON, the utility will automatically parse it into its appropriate JS type.

API

getDataAttributes(el: HTMLElement): Record<string, any>

  • el: The HTML element from which you want to retrieve the data attributes.

Returns a JavaScript object containing the data attributes and their parsed values.

Example

Given the following HTML:

<div
  class="example"
  data-name="John Doe"
  data-age='30'
  data-hobbies='["reading", "cycling"]'
>
  Example Element
</div>

And the usage:

const element = document.querySelector('.example');
const dataAttributes = getDataAttributes(element);

console.log(dataAttributes);

This will output:

{
  name: "John Doe",
  age: "30",
  hobbies: ["reading", "cycling"]
}
2.0.2

9 months ago

2.0.1

9 months ago

1.2.12

10 months ago

1.2.11

10 months ago

1.2.9

12 months ago

1.2.10

12 months ago

1.2.8

1 year ago

1.2.7

1 year ago

1.2.4

1 year ago

1.2.3

1 year ago

1.2.2

1 year ago

1.2.1

1 year ago

1.2.0

1 year ago

1.1.16

1 year ago

1.1.15

1 year ago

1.1.14

1 year ago

1.1.13

1 year ago

1.1.12

1 year ago

1.1.11

1 year ago

1.1.10

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.1.1

2 years ago

1.1.2

1 year ago

1.0.12

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.1

2 years ago