Namespace: Elements:getData

Elements:getData

Methods

getData(node, propertiesopt) → {*|Object|null}

Returns the element's currently set data attribute value(s).

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 data-my-naughty-dog property does not magically become myNaughtyDog on access, but keeps the original notation, just losing the prefix, so access it, by using my-naughty-dog
  2. All property values are treated as JSON first and foremost, falling back to string values, if the value is not parsable. This means, that {"foo" : "bar"} becomes an object, [1, 2, 3] becomes an array, 42 becomes a number, true becomes a boolean and null becomes a null-value. But foobar actually becomes the string "foobar". JSON-style double quotes are removed, when handling a single string.

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 read data from

properties String | Array.<String> <optional>
null

if set, returns value(s) of that specific property/properties (single value for exactly one property, dictionary for multiple), if left out, all properties are returned as a dictionary object

Source:
See:
Throws:

error if node is not a usable HTML element

Returns:
JSON-parsed attribute value(s) with string fallback; either a single value for exactly one property, a dictionary of values for multiple or a call without properties (meaning all) or null, in case no data was found
Type
* | Object | null
Example
getData(createNode('<div data-my-naughty-dog="42"></div>'), 'my-naughty-dog')
=> 42
getData(createNode('<div data-my-naughty-dog='{"foo" : [1, "two", true]}'></div>'), 'my-naughty-dog')
=> {"foo" : [1, "two", true]}
getData(createNode('<div data-my-naughty-dog='1, "two", true'></div>'), 'my-naughty-dog')
=> '1, "two", true'
getData(createNode('<div data-my-naughty-dog="42" data-foo="true" data-bar="test"></div>'), ['foo', 'bar'])
=> {"foo" : true, "bar" : "test"}
getData(createNode('<div data-my-naughty-dog="42" data-foo="true" data-bar="test"></div>'))
=> {"my-naughty-dog" : 42,"foo" : true, "bar" : "test"}