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


this question has answer here:

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

heres fiddle play with

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

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -