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
source share
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.

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

+1
source

jQuery doesn't actually update HTML when storing data using the data attribute. Visual attributes allow you to set the iinitial value of the data for the attribute, except that jQuery simply caches the value for the DOM node object.

+1
source

Source: https://habr.com/ru/post/1479228/


All Articles