4

I am generating json and storing it as a data attribute. e.g.

  data-categories="{"2":{"categoryId":"2","name":"how to's"},"5":{"categoryId":"5","name":"about us"},"6":{"categoryId":"6","name":"proucts"}}"

When I later try to edit and save the new json it is not being saved and the old dat still exists.

e.g.

//get the existing categories var currentCategories = $('li#'+ $(this).data('backgroundid')+' .categoryTags .addCategory').data('categories'); //get then name and if from the at to link
var newCategory = {'tagid': $(this).data('categoryid'), 'name': $(this).data('categoryname')} currentCategories=[$(this).data('backgroundid')].push(newCategory); //when I log the object here it is fine contains the old categories and the new category

//save the new string back to the data attribute of li elsewhere on page
    $('li#'+ $(this).data('pageid')+' .categoryNames .addCategory').data('categories',currentCategories);

But the the data is still the same in the dome and when I try to reference it later

Barry Hamilton
  • 943
  • 3
  • 15
  • 35
  • Please include the code you're using to actually select the `data-categories` attribute, since without it, `this` has no context. – Brandon Anzaldi Jan 16 '15 at 12:35
  • first of all the json its not ok, data-categories="{ .... }" should be data-categories = { ... } – hiero Jan 16 '15 at 12:36
  • `data is still the same in the dome` i guess you mean DOM. Ya, `data()` method doesn't update the data attribute. To update the attribute, use `attr()` method but missing some context to make your question clear enough. Why would you need to update the attribute? – A. Wolff Jan 16 '15 at 12:39

1 Answers1

7

I think you may be being mislead by what you're seeing in the element's actual DOM attribute (as viewed in the developer tools).

When creating a new jQuery object, any HTML5 data-* attributes found on the affected nodes, if any, are automatically transferred to the jQuery instance's internal .data() storage. So "data-categories" is being swept into an object by jQuery upon creation.

When jQuery's .data() method is used, it won't attempt to update the underlying DOM, since that'd use twice as much overhead (manipulating the DOM is slower than working in pure JavaScript).

In other words, jQuery.data is not the same as using HTML5 data- attributes.

If you were to call jQuery(el).data("categories") after assigning it the modified category hash, it'd most likely return what you expect. :)

  • 1
    your exactly right you have explained exactly what I was starting to observe in the dom. I have been running on a wild goose chase and the issue I am trying to solve has nothing to do with the data not being stored it's just as you explained. – Barry Hamilton Jan 16 '15 at 13:24
  • We've all been there, mate... myself included. :( –  Jan 16 '15 at 13:25