4

So I'm basically adding some elements to the DOM on the fly. I can use method like .addClass on them before they exist, and the class is appended to the DOM along with the element, but when I use the .data() method to add a data attribute, the data isn't appended to the DOM with the element. Am I missing something here or do I really have to wait until the element exists in the DOM to add data to it?

PS. Using jquery 1.9.1

HERES A FIDDLE FOR YOU TO PLAY WITH

JS

var widget = $("<div>");
widget.addClass("banana");
widget.data('color', 'brown');
widget.appendTo('#container');

HTML

<div id="container">

</div>

And theres some nice css there so you know where to click to inspect and see the data attribute isn't(or hopefully is) added.

My expected result is

<div id="container">
    <div class="banana" data-color="brown"></div>
</div>

Cheers.

Rooster
  • 9,954
  • 8
  • 44
  • 71

2 Answers2

22

The .data() method does not create [data-*] attributes on DOM nodes. It simply associates the data object with the DOM node. It does initialize with values from [data-*] attributes if any exist, but this is not the same thing.

If you need to set an explicit [data-*] attribute value (such as a styling hook with CSS), then you need to use .attr()

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • ah. I see. After reading the link you posted and this answer I see why I was confused. I don't usually use the .data() in quite the way I'm using it here. thanks for doing my research for me! – Rooster Aug 19 '13 at 21:37
2

This seems to work for me,

var widget = $("<div>");
widget.addClass("banana");
jQuery.data(widget, 'color', 'brown');
widget.appendTo('#container');
console.log(jQuery.data(widget));

Updated fiddle: http://jsfiddle.net/rTfvG/3/

PherricOxide
  • 15,493
  • 3
  • 28
  • 41