1

I have the JS and HTML Code as below

var a=$("li").data("item");
console.log($("li").data("item").type);
  <li  data-item="{&quot;contentId&quot; : 5,&quot;type&quot; : &quot;PROGRAM&quot;, section_type:  &quot;PROGRAM_SECTION&quot;, &quot;active&quot;:&quot;false&quot;  }">data</li>

Trying to get the JS Object's type property value in the data-item attribute using the code

var a=$("li").data("item");
console.log($("li").data("item").type);

But I got var a=$("li").data("item"); as string, even JSON.parse(a) also not working see the screenshot enter image description hereand codepen http://codepen.io/shmdhussain/pen/VvXKLr

Please help me in parse the data. Thanks in advance for any help.

0

3 Answers 3

1

OK, so I found a few things wrong:

1: It should be

$("li").data("sna-item");

Also, you have an error in your data-sna-item (It's not valid json). There are no quotes around section_type

Here's an updated codepen: http://codepen.io/anon/pen/gaewrd

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

2 Comments

Thanks FrankerZ for spotting the mistake.
For better readability I'd write <li data-sna-item='{"contentId": 5, "type": "PROGRAM", "section_type": "PROGRAM_SECTION", "active": false}'>data</li> codepen.io/anon/pen/EVEgpv
1

the problem is that your data is using &quot; when it should be using " so you need to replace &quot; with "

use this

JSON.parse($("li").data("item").replace(/&quot;/g,'"')).type;

assuming $("li").data("item") yields the data you wish to parse.

Comments

1

Theres a few issues... try using the below HTML and JS instead.

HTML

<li data-item="{&quot;contentId&quot; : 5,
&quot;type&quot; : &quot;PROGRAM&quot;,
&quot;section_type&quot;:  &quot;PROGRAM_SECTION&quot;, 
&quot;active&quot; :&quot;false&quot;} ">data</li>

JS

var item = $("li").data("item");
var json = JSON.parse(item);    
$("li").text(json.type);

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.