1

Im trying to get data out of a data attribute using jquery.

Heres what I have:

<div id="x" data-foo="{top:'100', left:'40', width:'50'}">

and in javascript:

x = $('#x').data();

console.log( x.foo.top ) //undefined

Ive tried JSON parse as well, but I get errors about unexpected tokens then.

2
  • data.foo is a string. It doesn't automatically know that the string value contains JSON content. Commented Apr 3, 2019 at 18:23
  • @amy yeah that seems to be the root of the problem Commented Apr 3, 2019 at 18:27

3 Answers 3

2

You can get data with jQuery attr x = $('#x').attr('data-foo'); And then parse it to json like: var data = JSON.parse(x)

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

3 Comments

.data('foo') gets the attribute value. No need for attr.
Same issue. The challenge is to set the data in the attribute with the HTML. It did get me thinking about how the string was formatted though. I think I have the answer, one sec to confirm.
Yep, if you format the string properly, you can use it as a JSON object, otherwise you get errors trying to parse or access the keys. Proper string in my eample would be (note the use of quotes): '{"top":"100", "left":"40", "width":"50"}'
1

Please arrange your code like this

 <div id="x" data-foo='{"top":"100", "left":"40", "width":"50"}'> 

 In JSON, Key will be double quote. 

4 Comments

@JasonLough Please go to the link and test it. jsfiddle.net/ahscse/gvu48Lqc
@JasonLough If this is the answer, click the checkmark to accept it. See meta.stackexchange.com/questions/5234/…
As this question has been downvoted most likely because of suggesting to use single instead of double quotes: both are legit. I would recommend to stick to either single or double quote and use &quot; inside your data-foo value, otherwise this may be a cause of problems if someone else has to maintain your code.
@JasonLough you can click Check mark (it will be selected) but not up or down Key
0

What you have in data-foo is the string for a Javascript Object Literal and not JSON

Firstly, you need your JSON formatted properly. See below.

<div id="x" data-foo='{"top":"100", "left":"40", "width":"50"}'></div>

Read more about that here.

https://medium.com/@easyexpresssoft/object-literal-vs-json-7a2084872907

Then, use JSON.parse() to get your data

var x = JSON.parse($('#x').attr("data-foo"));
alert( x.top );

Hope it helps

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.