Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.data() not returning undefined

Tags:

html

jquery

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?

like image 241
Anthony Avatar asked Jun 09 '26 14:06

Anthony


1 Answers

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

like image 196
Ionică Bizău Avatar answered Jun 11 '26 12:06

Ionică Bizău