I'm playing around with the attr-data-* attributes of HTML5 and the corresponding javascript dataset
I'm doing alot of dynamic form processing, so I end up getting stuff like this:
<input data-feaux="bar" data-fizz="buzz"/>
Since HTMLElement.dataset
returns a DOM string map
, the only way I can figure out how to convert it into an native object is:
var obj = JSON.parse(JSON.stringify(input_el.dataset))
Is there a better way to do this?
Edit:
Why would I want to do this? Let's say I have many, many of these elements. I want to loop through them all and push them into an array for processing later, i.e.
elements = document.querySelectorAll("input") my_data_array = [] for(var i = 0; i < elements.length; i++) { my_data_array.push(elements[i].dataset) }
Now I have an array of objects, i.e. [{feaux: "bar", fizz:"buzz"}....]
that I can work with.
However, when I don't convert the DOM string map
into an object, the array doesn't get populated (i.e. the code above doesn't work)
Edit 2
Looking closer, it is actually a DOM string map
, not an object
. Correcting typos in the original question to reflect this.
The data-* attribute is a Global Attribute, and can be used on any HTML element.
In short, a data attribute is a single-value descriptor for a data point or data object. It exists most often as a column in a data table, but can also refer to special formatting or functionality for objects in programming languages such as Python.
data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
Approach: First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.
You can use Object.assign
Object.assign({}, element.dataset)
For browsers that doesn't support Object.assign you can use polyfill
in es6 you can use the object spread.{ ...element.dataset }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With