Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery retrieve relatedTarget.data('url') value

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:

screenshot

how can I retrieve it? thanks! Joe

like image 937
Joe Avatar asked Oct 21 '16 09:10

Joe


3 Answers

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.

like image 148
James Donnelly Avatar answered Sep 29 '22 11:09

James Donnelly


$(e.relatedTarget).data('url');

This is a js element. To use data() function, you have to make that element a jquery element.

like image 30
Adrian C. Avatar answered Sep 29 '22 11:09

Adrian C.


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(…)

like image 35
CBroe Avatar answered Sep 29 '22 11:09

CBroe