I trying to use .data to get a value out of an attribute.
HTML
<div class="like" data-postid="903282304865jh"> </div>
JS
$(".like").click(function(event){
var postID = $(event.target).data('postid');
console.log(postID);
});
I get undefined returned in my console. Whats going on here?
Use $(this) instead of $(event.target):
var postID = $(this).data('postid');
Your code works good if there are not other elements in div.
Also consider comparing the target.event with this:
event.targetThe DOM element that initiated the event. read more
thisIn jQuery, the element being acted upon is often passed to the function parameter of a jQuery function as this. It can be made into a jQuery element object by using $(this). read more
Your code becomes:
$(".like").click(function(event){
var postID = $(this).data('postid');
alert(postID);
});
As HTML example can be the following:
<div class="like" data-postid="903282304865jh"><i>A</i> Test</div>
JSFIDDLE
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