Anthony
Anthony

Reputation: 2416

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

Upvotes: 2

Views: 3974

Answers (4)

lakshman_dev
lakshman_dev

Reputation: 94

This worked for me :

var target = event.target;

var getData = $(target).data('user-id');

Upvotes: 1

Kousik
Kousik

Reputation: 22425

$(".like").click(function(event){ 
    var postID = this.attributes['data-postid'].nodeValue
    console.log(postID);
});

or

$(".like").click(function(event){ 
    var postID = $(this).data('postid')
    console.log(postID);
});

Upvotes: 1

Ionică Bizău
Ionică Bizău

Reputation: 113365

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

Upvotes: 7

colestrode
colestrode

Reputation: 10658

Change event.target to this. event.target will be the element that was clicked, so it could be any child of your div. this will be the element referenced by your selector:

$(".like").click(function(event){ 
      var postID = $(this).data('postid');
      alert(postID);
});

Working Demo

Upvotes: 4

Related Questions