html - Adding data attributes to elements not yet inserted into DOM in jquery -
this question has answer here:
- jquery data vs attr? 3 answers
so i'm adding elements dom on fly. can use method .addclass on them before exist, , class appended dom along element, when use .data() method add data attribute, data isn't appended dom element. missing here or have wait until element exists in dom add data it?
ps. using jquery 1.9.1
js
var widget = $("<div>"); widget.addclass("banana"); widget.data('color', 'brown'); widget.appendto('#container');
html
<div id="container"> </div>
and theres nice css there know click inspect , see data attribute isn't(or is) added.
my expected result is
<div id="container"> <div class="banana" data-color="brown"></div> </div>
cheers.
the .data()
method not create [data-*]
attributes on dom nodes. associates data object dom node. does initialize values [data-*]
attributes if exist, not same thing.
if need set explicit [data-*]
attribute value (such styling hook css), need use .attr()
Comments
Post a Comment