Anthony Anthony - 1 month ago 5
jQuery Question

.data() not returning undefined

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?

Answer

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.target

The DOM element that initiated the event. read more


this

In 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

Example

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