1

Given the below code I expect both foo and bar to have a div inside of them with the appropriate data attribute, but only the one using attr works. Am I missing something? Is this possible? Can someone explain /why/ this works the way it does? I tried to look at the api docs for each method, but didn't see anything to suggest that it shouldn't work.

<div id="foo">asdd</div>
<div id="bar">asdasd</div>

$("#foo").append($('<div>').attr("data-something", "a value"));
$("#bar").append($('<div>').data("something", "a second value"));

http://jsfiddle.net/bUr7E/

http://api.jquery.com/data/#data1

https://api.jquery.com/attr/#attr2

Jazzepi
  • 5,259
  • 11
  • 55
  • 81

3 Answers3

3

jQuery does not store data on the DOM, it uses an internal map

ThaiKov
  • 175
  • 9
3

You can do that, but what you're expecting to happen with .data() is not how that method works. The .data() method will read values from data-foo attributes, but it won't ever create or modify such attributes.

From the API documentation you linked:

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

In your own fiddle, you should be able to prove to yourself from the debug console that the second <div> you create does in fact have that data stored.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

If you're interesting in providing data and pairing it with DOM elements, you might want to consider using D3: http://d3js.org

lyyons
  • 393
  • 3
  • 11