Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we assign an object to a html element in plain JavaScript without jQuery

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

like image 493
xander cage Avatar asked Oct 24 '25 05:10

xander cage


1 Answers

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.

like image 183
Phillip Avatar answered Oct 26 '25 19:10

Phillip