0

I have a string like:

<span class="someClass" id="skAdmin" data-options='{
   "elmsList" : {
      "#skAdmin" : {
         "action" : "replace",
         "replaceWith" : "<input class=\"form-control\">"
         }
      }
   }'>Name</span>  

Now (when i make a click on this span) I need to replace this element (span) by element in data-options (input). And at the same time i need to add all span attributes to input element, but input is just a text (not an object). How can I convert this to object?

5
  • 3
    JSON.parse()! Commented Oct 29, 2013 at 13:14
  • @ComFreek you don't need to a jQuery will have already done that. In memory this data-attribute will already be an object. Commented Oct 29, 2013 at 13:15
  • @RoryMcCrossan jQuery? JSON.parse() is not jQuery. See Sirko's answer. Commented Oct 29, 2013 at 13:16
  • @ComFreek obviously. However the OP tagged this question as jQuery and as such JSON.parse seems redundant. Commented Oct 29, 2013 at 13:20
  • @RoryMcCrossan I see. I didn't know that jQuery would automatically parse JSON. +1 for you. Commented Oct 29, 2013 at 13:21

2 Answers 2

2

Use JSON.parse() to retrieve an object:

var obj = JSON.parse( document.querySelector( '#skAdmin' ).dataset.options );

// or

var obj = JSON.parse( document.getElementById( 'skAdmin' ).dataset.options );

Edit

As the comments note, if you are already using jQuery, all data-* attributes will already be parsed into jQuery's data object. So you can access it by just using:

var obj = $( '#skAdmin' ).data( 'options' );
Sign up to request clarification or add additional context in comments.

3 Comments

jQuery also exposes a parseJSON() method should all the browsers you target not support JSON.parse().
querySelector is unnecessary, use document.getElementById().
or var obj = $('#skAdmin').data('options');
1

You do not need to parse this value as jQuery will have already done this for you when it stored it in it's in-memory cache. Therefore you can access it like an object:

$('.someClass').click(function() {
    var replaceWith = $(this).data('options').elmsList['#skAdmin'].replaceWith;
    $(this).replaceWith(replaceWith)
});

Example fiddle

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.