简体   繁体   中英

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

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.

Here is another approach. This is a good time to learn about Map which is similar to an object but the key can be any type, not just strings. You can use the element as a key and the object as the value.

const elementMap = new Map();
const myElement = document.querySelector("#myElement");
const myObject = {x: 0, y: 0, z: 0};
elementMap.set(myElement, myObject);
...
//later we can access the object by that element
const myElement = document.querySelector("#myElement");
const myObject = elementMap.get(myElement);

Here are two big advantages of this approach.
1. No need to worry about name collisions with properties of the HTML element, or possibly other code modifying the element's properties.
2. The object is the same object you originally had, which can be important if you care about the reference which is not preserved if you use the JSON string solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM