HasanAboShally
HasanAboShally

Reputation: 18675

Can't set .data() for an element

I'm not able to add data to a dynamically added element:

var newItem = "<li>" + poi.Title + "</li>";
$(newItem).data('poiID', poi.ID);
$(newItem).data('poiTitle', poi.Title);

I've tried to add this:

alert($(newItem).data('poiID'));

right after the above line, but I keep getting "undefined".

Upvotes: 0

Views: 315

Answers (3)

Shawn Chin
Shawn Chin

Reputation: 86854

That's because everytime you do $(newItem) you're creating a new element and you're not actually storing a reference to it.

Try:

var newItem = $("<li>" + poi.Title + "</li>");  /* create element as newItem */
newItem.data('poiID', poi.ID);                  /* add data to existing elem */
alert(newItem.data('poiID'));                   /* peek at your data */

Do note that at this point your new element is not yet attached to your DOM. To have it appear on the page, you'll need attach newItem using methods such as append(), prepend(), etc.

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

Change your code like so:

var newItem = $("<li>" + poi.Title + "</li>");
newItem.data('poiID', poi.ID);
newItem.data('poiTitle', poi.Title);

...

alert(newItem.data('poiID'));

Example fiddle : http://jsfiddle.net/P4HWb/

Upvotes: 2

JoeFletch
JoeFletch

Reputation: 3960

Your newItem is not in the DOM yet. Append it and then you can add .data() to it.

Or you can do something like this.

var newItem = $("<li>" + poi.Title + "</li>");
$(newItem).data('poi', poi); //That way the whole object is added to the element.

Then append it to the DOM.

Upvotes: -1

Related Questions