The shape of the dataset data.
Tag name of element with which the dataset is associated.
Creates a new instance of a DatasetWrapper
class to manage the dataset
property of the corresponding target
. Optionally pass in initialData
that can fully match the shape specified in the DS
generic or partially.
The shape of the dataset data.
elements!InvalidElementError
if the specified target
wasn't found.
Builds an object with all defined dataset attribute values. Note that the
return value is a Partial
because the expected shape of the dataset
specified in the DS
generic doesn't necessarily correspond to dataset
properties that exist on the element.
Object with dataset entries that exist.
HTML
<div id="example" data-count="20">Example</div>
Code
const element = findElement("#example");
const data = wrapDataset<{ count: number; label: string }>(element);
// Note that `label` is missing because there is no `data-label` attribute
// on the specified element:
const entries = data.getAll();
// { count: 20 }
Wrapper for managing the dataset property on an element.
Trying to work with the
dataset
property using TypeScript is not great. You have to repeatedly perform a bunch of type checks, which is tedious and results in overly-verbose code. This class makes it much easier to get and set properties of thedataset
(which map to the correspondingdata-*
attributes on an element).The
dataset
property is a (very barebones) DOMStringMap. This wrapper class enables you to get and set values of any type that can be stringified while retaining type safety via theDS
generic passed in.See usage examples in
wrapDataset
.