Reputation: 18675
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
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
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
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