Skip to content
Toke Voltelen edited this page Dec 3, 2016 · 4 revisions

data(elm, dataName[, value])

Get/set the value of a 'data-' attribute on a given DOM element

Parameters

  • elm (HTMLElement) - The DOM element to fetch the data from
  • dataName (String) - Name of the 'data-' attribute to handle (eg. id -> data-id)
  • value (String|Number) - [optional] Value to insert into the 'data-' attribute
  • returns {String} - Data found in the 'data-' attribute (or the old value if {value} is defined)

Usage

Get value

import data from 'vanillajs-browser-helpers/data';

// Get value of a data attribute
const value = data(element, 'name');

// use camelCase
const value = data(element, 'camelCaseName');

// or dashed
const value = data(element, 'dashed-name');

Set value

import data from 'vanillajs-browser-helpers/data';

// Set value of a data attribute
const oldValue = data(element, 'name', 'value');

// use camelCase
const oldValue = data(element, 'camelCaseName', 'value');

// or dashed
const oldValue = data(element, 'dashed-name', 'value');
Clone this wiki locally