4

strange problem - maybe I'm missing something.

My code:

HTML

<div id="container">
    <span data-foo="initial content">Blabla</span>    
</div>

jQuery

console.log($("span").data("foo")); //initial content
console.log($("#container").html()); //<span data-foo="initial content">Blabla</span>   

$("span").data("foo", "new content");

console.log($("span").data("foo")); //new content
console.log($("#container").html()); //<span data-foo="initial content">Blabla</span>   <----- ?!?!?!?!

The very last line shows the unexpected behavior. The modification done previously by .data("foo", "new content") does not reflect when reading the content via .html()

Fiddle: http://jsfiddle.net/sSZjh/

David Müller
  • 5,291
  • 2
  • 29
  • 33

2 Answers2

1

.data in jQuery only reads data- attributes, but doesn't set them. You need to use .attr('data-...') to set the data attribute.

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

From http://api.jquery.com/data/

Dogbert
  • 212,659
  • 41
  • 396
  • 397
1

jQuery does not actually update the HTML when you store data using the data attribute. The visual attributes are there for you to set the iinitial data value for an attribute, beyond that jQuery simply caches the value against the DOM node object.

David Barker
  • 14,484
  • 3
  • 48
  • 77