moshe
moshe

Reputation: 3

How to add data to jquery created element?

Adding data to new element:

var ComBox = $('<div></div>').addClass('commentBox');
$.data(ComBox, 'ChannelID', 5);
$('body').append(ComBox);

When trying to get the data, results in undefined..

var cID = $('.commentBox').data('ChannelID');
console.log('cID : '+cID );

Upvotes: 0

Views: 1808

Answers (2)

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91379

$.data expects a DOM element, not a jQuery object. Either use:

$.data(ComBox[0], 'ChannelID', 5);

Or the more convenient .data() function, as suggested by @gdoron:

ComBox.data('ChannelID', 5);

DEMO.

Upvotes: 0

gdoron
gdoron

Reputation: 150313

Replace this:

$.data(ComBox, 'ChannelID', 5);

With this:

ComBox.data('ChannelID', 5);

It uses this function

Best practice note, you better prefix your jQuery object with $ meaning:
ComBox => $comBox

Upvotes: 5

Related Questions