• Creates a new DatasetWrapper instance for managing the dataset property on the target element. Optionally pass in initialData that can fully or partially match the shape specified in the DS generic.

    Type Parameters

    • DS extends AnyDatasetShape

      The shape of the dataset data.

    • TN extends TagName = "*"

      Tag name of element with which the dataset is associated.

    Parameters

    • target: Target

      Element, EventTarget, or CSS selector.

    • OptionalinitialData: Partial<DS>

      Optional full or partial dataset that corresponds to the dataset shape.

    Returns DatasetWrapper<DS, TN>

    DatasetWrapper instance associated with target.

    HTML (Before)

    <div
    id="example"
    data-is-active="false"
    data-count="30"
    data-label="Example"
    >
    ...
    </div>

    Code

    const element = findElement("#example")!;

    type Shape = {
    isActive: boolean;
    isInvalid: boolean | undefined;
    count: number;
    label: string;
    status: string | undefined;
    }

    // You can pass in initial dataset which will be added to the element's
    // dataset (as well as set as attributes on the element).
    const dataset = wrapDataset<Shape>(element, {
    isActive: false,
    count: 30,
    label: "Example",
    });

    // Returns the value for the specified key:
    dataset.get("count");
    // 30

    // `set` returns the `Dataset` instance so you can perform
    // other operations:
    dataset
    .set("count", 40)
    .get("count");
    // 40

    // Remove from the element:
    dataset.remove("label");

    // Update existing entry or add new one if not present:
    dataset.set("status", "warning");

    // Sets multiple entries on element:
    dataset.setAll({ isActive: true, isInvalid: false });

    // Returns an object matching `Shape`:
    dataset.getAll();
    // { isActive: true, isInvalid: false, count: 40, status: "warning" }

    // Get attribute name for an entry:
    dataset.attributeNameFor("isActive");
    // "data-is-active"

    HTML (After)

    <div
    id="example"
    data-is-active="true"
    data-is-invalid="false"
    data-count="40"
    data-status="warning"
    >
    ...
    </div>