JQuery.data () vs..html ()
strange problem - maybe I missed something.
My code is:
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 unexpected behavior. Changes made earlier to .data("foo", "new content") are not reflected when reading content through .html()
Violin: http://jsfiddle.net/sSZjh/
+4
2 answers
.data in jQuery only reads data- attributes, but does not set them. To set the data attribute, you must use .attr('data-...') .
As with jQuery 1.4.3, HTML data attributes will automatically be inserted into the jQuery data object. Attribute handling with inline dashes has been changed in jQuery 1.6 to meet the W3C HTML5 specification.
+1