I have this code in a function that creates an anchor, stores data and appends it to a div element
var x = $("<a class='randomclass'></a>");
x.data('foo', 'bar');
console.log(x.data());
...
$("<div></div>").append(
x
);
...
Now when I try to have an event handler that gets that data back, it shows that its undefined. I have tried different ways to access element but they all return no data
$("body").on("click", "a.randomclass", function (event) {
event.preventDefault();
console.log( $(event.target).data('foo') );
console.log( $(event.currentTarget).data('foo') );
console.log( $(this).data('foo') );
});
Any reason why this is so?
EDIT: Fixed typo.
Ok I think I found the answer guys.
The problem is that I got the markup of the element using .html() and passed it to a function.
I guess that means that any data of that element is lost since .html() just gets the string representation of that element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With