3

My data-attribute looks something like this:

data-image="[object Object],[object Object] "
2
  • 1
    Can you include HTML at Question? How is data-* attribute set? Commented Oct 17, 2017 at 5:39
  • Please add more details to the question. What is the question here ? What are you trying to do and how ? Commented Oct 17, 2017 at 5:43

3 Answers 3

2

Only string/number can be stored in attributes. So just store the src of the image if you want to store image details. If for some reason you want to store an object, convert it to string first and then later when you retrieve it, convert to object.

//Convert to String 
var mystring = JSON.stringify(myobject); // store this in the attribute. 

//Convert to Object while retrieving 
var myobj = JSON.parse(mystring);
Sign up to request clarification or add additional context in comments.

Comments

2

If the data-* attribute is set at HTML use valid JSON for the value, JSON.stringify() and JSON.parse() to set and get the data-* attribute value as a JavaScript object. You can get and set the HTML data-* attribute using HTMLElement.dataset

console.log(
  JSON.parse(
    document.querySelector("div").dataset.image
  )
)
<!-- set `data-*` attribute value as valid `JSON` -->
<div data-image='[{"a":123}, {"b":456}]'></div>

Comments

1

Actually when you retrieve this, you will get only string with value [object Object],[object Object]. You keep your data in the data-attribute with wrong syntax. Try first make your value of data-image into JSON format and then keep in the data-image attribute. After that you can retrieve your data via (see comments)

const dataArray = [ { name: 'Name1' }, { name: 'Name2' } ];
const div = $('#div');

div.data('image', JSON.stringify(dataArray)); // keep the attribute as string 

const retrievedDataImageAsJSON = div.data('image'); // retrieve the data attribute as string
const dataObj = JSON.parse(retrievedDataImageAsJSON); // parse from JSON into JS objects.

console.log(dataObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div' data-image>

</div>

Comments

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.