Namespace: Elements:setData

Elements:setData

Methods

setData(node, dataSet, singleValueopt, nullable) → {Object.<String, *>|*|null}

Writes data to an element, by setting data-attributes.

Setting a value of undefined or an empty string removes the attribute.

This method has two major differences from the standard browser dataset-implementations:

  1. Property names are not handled camel-cased in any way. The data attribute my-naughty-dog property is not magically created from myNaughtyDog, but the original notation will be kept, just adding the prefix, so set data-my-naughty-dog by using my-naughty-dog
  2. All property values are treated as JSON first and foremost, falling back to basic string values, if the value is not stringifiable as JSON. If the top-level value ends up to be a simple JSON string like '"foo"' or "'foo'", the double quotes are removed before writing the value.

Keep in mind that things like new Date() will not work out of the box, since this is not included in the JSON standard, but has to be serialized/deserialized.

Parameters:
Name Type Attributes Default Description
node HTMLElement

the element to write data to

dataSet Object.<String, *> | String

the data to write to the element, properties have to be exact data-attribute names without the data-prefix, values are stringified (first with JSON.stringify and then as-is as a fallback), if value is a function it gets executed and the return value will be used from there on; if this is a string, this defines a single property to set, with the singleValue being the value to set

singleValue * <optional>
<nullable>
null

if you only want to set exactly one property, you may set dataSet to the property name as a string and provide the value via this parameter instead

Source:
See:
Throws:

error if node is not a usable HTML element or if dataSet is not a plain object if no single value has been given

Returns:
the value(s) actually written to the element's data-attributes as they would be returned by getData (removed attributes are marked with `undefined`); null will be returned if nothing was changed; if only a single value was set, only that value will be returned
Type
Object.<String, *> | * | null
Example
setData(element, {foobar : 'hello kittens!'});
=> {foobar : 'hello kittens!'}
setData(element, 'foobar', 'hello kittens!');
=> 'hello kittens!'
setData(element, {foobar : {a : 'foo', b : [1, 2, 3], c : {d : true}}});
=> {foobar : {a : 'foo', b : [1, 2, 3], c : {d : true}}}
setData(element, 'foobar', {a : 'foo', b : [1, 2, 3], c : {d : true}});
=> {a : 'foo', b : [1, 2, 3], c : {d : true}}
setData(element, {foobar : () => { return 'hello kittens!'; }});
=> {foobar : 'hello kittens!'}
setData(element, {foobar : undefined});
=> {foobar : undefined}
setData(element, boofar, '');
=> undefined