- Source:
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:
- Property names are not handled camel-cased in any way.
The data attribute
my-naughty-dog
property is not magically created frommyNaughtyDog
, but the original notation will be kept, just adding the prefix, so setdata-my-naughty-dog
by usingmy-naughty-dog
- 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:
- 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