jQuery.data() returns 'undefined' when retrieving data from dynamic elements
javascript, jquery
Solution
`jQuery.data()` takes a raw DOM element, not a jQuery object.
You need to either pass `this` directly, or call the instance method (`$(this).data()`)
Problem
My case is very simple, I just tried to store data into an element which `appended` in the `DOM` dynamically. My problem is, whenever I tried to retrieve the data through the immediate `appended object`, the value is returning fine, but through the object returned from the `click` event through `on` function it is returning `undefined`. I searched about this earlier, but people in stackoverflow were just suggested about removing the camel casing etc. That did not help me out in my case. Any suggestions or fix will be more helpful. My code: ``` $(document).ready(function(){ xElement = $('<li class="test">click this (because this contains data)</li>').appendTo('ul'); jQuery.data(xElement,"val","value1"); alert(jQuery.data(xElement,'val')); $(document).on('click','ul li',function(){ alert(jQuery.data($(this),'val')); }); }); ``` A Fiddle : Here