0

I have this scenario where i need to assign a java-script object to div attribute.

var temp["name"]="first";

i assigned it to a div tag attribute using Jquery.

div.attr('data-polygon',temp);
Object [ <div#image01> ]

when i try to retrieve it , it does not come back same.. it is converted as String.

div.attr('data-polygon');
"[object Object]"

Any proper option / alternate to retain the object in attribute? please let me know

1 Answer 1

2

Attributes are always strings.

Here are two options for doing this; since you're already using jQuery, the first is probably best:

jQuery's data

jQuery provides the data method for doing this:

// Setting -- notice no "data-" prefix
div.data("polygon", temp);

// Retrieving
varName = div.data("polygon");

Under the covers, traditionally data assigns the element a unique ID and manages a data cache for the element, separate from it. I think in the v3 branch they've updated it to actually store the data on the element (there were memory issues with doing that in Internet Explorer 8 and earlier, which is why jQuery didn't do it before).

Assign it as your own "expando" property

If you don't need to support Internet Explorer 8, you can just create a property on the actual DOM element.

// Setting
rawDiv.myUniquePrefixToAvoidConflicts_polygon = temp;

// Getting
varName = rawDiv.myUniquePrefixToAvoidConflicts_polygon;

Note that to avoid conflicts with the many predefined properties elements have, and future ones they don't have yet, you'll want to use a likely-unique prefix.

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

2 Comments

Hi @t-j-crowder, i tried to load multiple data attributes to a div tag .. but only i can see the last loaded attribute.. others are empty value.. any idea ?
@jmanoj86: I can't help with that without seeing the code (ideally a runnable MCVE using Stack Snippest). But it would be a separate question.

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.