Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 855
Rooster Avatar asked Nov 30 '22 01:11

Rooster


2 Answers

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()

like image 59
zzzzBov Avatar answered Dec 04 '22 12:12

zzzzBov


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/

like image 32
PherricOxide Avatar answered Dec 04 '22 11:12

PherricOxide