I need to retrieve the value of data-url attribute from event.relatedTarget
I tried in many ways:
e.relatedTarget.data('url')
e.relatedTarget.attr('url')
e.relatedTarget.prop('url')
but it always return an error.. but the value is there:
how can I retrieve it? thanks! Joe
Seeing as you're directly accessing the event object itself, jQuery's attr()
and prop()
methods will not work here as this isn't a jQuery object. You'll notice that there is no data
key on the event object as well, instead the key is called dataset
. Furthermore, this isn't a function, so ()
brackets will not achieve anything here.
Instead of e.relatedTarget.data('url')
, you'll want to use:
e.relatedTarget.dataset['url']
Or:
e.relatedTarget.dataset.url
It's worth noting that this has significantly better performance than converting the event object into a jQuery object and calling one of jQuery's functions as the other answers here suggest as you have all the properties right there. All jQuery will do is convert it back into the object you already have and access the property in a very similar way to what I've included above, so rather than going directly from A to B, you'd end up going from A to C then back to A to B.
$(e.relatedTarget).data('url');
This is a js element. To use data() function, you have to make that element a jquery element.
e.relatedTarget
returns the reference to a DOM element, not a jQuery object.
So before you can call jQuery methods on it, you need to create a jQuery object from it:
$(e.relatedTarget).data(…)
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