I want to store an object as an attribute of an HTML element! Let's suppose I'm having a div element and when I click the div element I want to get the values of the object from the div element so that I can use it in the click function.
I've seen people doing it in jquery but I want it in pure javascript since I'm writing a typescript code and I don't want jQuery
ex:
var myNewObject={
"first_name": "Sam",
"last_name": "carter"
}
var div=document.getElementByID("myID");
div.setAttribute("myobject",myNewObject);
<div onclick="somefunc()>
</div>
function somefunc()
{
console.log(document.getAttribute("myobject").first_name);
}
Expected output:
Sam
Actual output:
Error
You can store any Javascript objects on an HTMLElement directly:
const div = document.createElement('div');
div.myobject = { hello: 'world' };
Only strings can be stored in attributes, and the string representation of an object is [object Object]. If you must use attributes you can serialize the object and store it and then deserialize it when you retrieve it again:
const obj = { hello: 'world' };
const a = document.querySelector('#a');
a.setAttribute('myobject', JSON.stringify(obj));
const obj2 = JSON.parse(a.getAttribute('myobject'));
console.log(obj2.hello);
<div id="a">Hello</div>
Storing state in DOM is generally considered bad practice in any case.
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