Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Object in data-attribute without jQuery

My question basically is exactly like this question. I am just wondering, if there is a way to achieve this without jQuery.

The following code does not work. I have also tried it with an array, but just like the object it is stored as a string. Is there something I am doing wrong, or is it just not possible in plain javascript?

var div = document.getElementById("testDiv");
var obj = {name: "Test1", value: 100};
div.setAttribute("data-obj", obj);

var arr = [59, 40, 3, 2, 1, 0];
div.setAttribute("data-arr", arr);

console.log("Object-Value: "+div.dataset.obj+"; Type: "+(typeof div.dataset.obj)+"; Name: "+div.dataset.obj.name);
console.log("Array-Value: "+div.dataset.arr+"; Type: "+(typeof div.dataset.arr)+"; Third Value: "+div.dataset.arr[2]);
<div id="testDiv">This is a test.</div>
like image 921
Fay Boisam Avatar asked Sep 02 '25 11:09

Fay Boisam


1 Answers

Use JSON.stringify() before storing the data in the attribute. It is basically serializing the data into a string.

var div = document.getElementById("testDiv");
var obj = JSON.stringify({name: "Test1", value: 100});
div.setAttribute("data-obj", obj);

var arrayAsJSON = JSON.stringify([59, 40, 3, 2, 1, 0]);
div.setAttribute("data-arr", arrayAsJSON);

Then use JSON.parse() after you fetch the attribute value and before presenting it. This will deserialize it back to a javascript object, array or simple value, depending on your case.

like image 136
zhulien Avatar answered Sep 04 '25 02:09

zhulien