Anthony Anthony - 1 year ago 96
jQuery Question

.data() not returning undefined

I trying to use .data to get a value out of an attribute.


<div class="like" data-postid="903282304865jh"> </div>


var postID = $('postid');

I get undefined returned in my console. Whats going on here?

Answer Source

Use $(this) instead of $(

  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:

The DOM element that initiated the event. read more


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


Your code becomes:

      var postID = $(this).data('postid');

As HTML example can be the following:

<div class="like" data-postid="903282304865jh"><i>A</i> Test</div>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download