Monday, 19 August 2013

Adding data attributes to elements not yet inserted into DOM in jquery

Adding data attributes to elements not yet inserted into DOM in jquery

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.
Cheers.

No comments:

Post a Comment