Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Data from .data() is lost [closed]

Tags:

jquery

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.

like image 627
developarvin Avatar asked Dec 04 '25 11:12

developarvin


1 Answers

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.

like image 83
developarvin Avatar answered Dec 06 '25 00:12

developarvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!