0

I have an attribute of a list object in html like this:

<ul>
<li id="myID" add-param="{"type1":"myType1","type2":"myType2"}">Test</li>
</ul>

Having the list item with specified ID, how could I get the value myType1,myType2 by the key type, type2 ?

Thanks.

2
  • 1
    add-param="{"type1":"myType1","type2":"myType2"}" won't work, try : add-param="{'type1':'myType1','type2':'myType2'}" Commented Jul 3, 2011 at 12:41
  • add-param="{"type1":"myType1","type2":"myType2"}" is working in Firefox 4.0.1 and in IE 7 also. And the answer by Dogbert is compatibly working with this. Commented Jul 4, 2011 at 7:23

1 Answer 1

3
var json = JSON.parse($('#myID').attr('add-param'));

alert(json.type1) # myType1

Some old browsers don't have JSON.parse, you'll need to use this - https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Sidenote: You should be using data attributes instead of defining your own custom attributes - http://ejohn.org/blog/html-5-data-attributes/

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

2 Comments

Please note that not all browsers support the JSON object.
I have included the json2.js file in my page. And this is working with IE 7 and FF 4.0.1. Is there any other browser that doesn't support this, or is this supported by all browsers?

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.