'Adding data to data attribute that contains array (HTML/Javascript)
I have a html code that has a data attribute named data-keys which is an array. I want to add values to this array by javascript. What function can I use in order to do this?
<input type="text" data-keys="[]">
Solution 1:[1]
While this is semi-possible for values that are serializable (objects, arrays, and primitives)...
const input = document.querySelector('input');
// retrieve array
const keysArr = JSON.parse(input.dataset.keys);
keysArr.push('foo');
// set array to dataset again
input.dataset.keys = JSON.stringify(keysArr);
// retrieve array to show that it's changed
console.log(input.dataset.keys);
<input type="text" data-keys="[]">
It's very, very strange. A much better approach would be to store the values in JavaScript instead. If you need to associate each input to an array, consider using a Map instead.
const input = document.querySelector('input');
const keysByInputs = new Map([
[input, []]
]);
// retrieve array
const keysArr = keysByInputs.get(input);
keysArr.push('foo');
// retrieve array to show that it's changed
console.log(keysByInputs.get(input));
<input type="text" data-keys="[]">
Solution 2:[2]
Since attribute values are strings, you will have to convert from string to JSON and vice versa. These functions will do just that:
Additionally, you'll want to use functions to get a hold of the element, as well as get and set its attribute(s). May I suggest these:
Alternatively to the more general purpose getAttribute() and setAttribute(), you could also use element.dataset() in your particular case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
| Solution 2 |
