4

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

1
  • 2
    Attributes are for simple data only. But you can attach anything to the element objects directly: document.getElementById('id_here').foobar = {"bar":"baz"}; localStorage or your own object to keep track of data might suit your needs better though. Commented Aug 23, 2019 at 10:34

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

hello @Phillip! The set attribute code worked! thanks a lot! I didn't get the idea of stringifying it earlier. Coming to the assigning of the object to HTMLElement directly, I'm not able to do that! I want you to know I'm using typescript! "I'm getting an issue property doesn't exist on HTMLElement"
You would either have to augment the HTMLElement (or the specific element) type with the property you wish to add, or just cast to any: (element as any).myobject = ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.