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.
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()
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With