Chandana Chandana - 5 months ago 9
Javascript Question

Jquery attribute value for current element

I am trying to find value of an attribute for clicked element. All elements are dynamically populated.

I am unable to get value of attribute. what may be the issue?

<span title="cancel work" class="cancel" myid="111"><i class="fa fa-stop"></i> Stop work</span>

$(document).on('click','.cancel',(function(){
alert($(this).attr("myid"));
}));


This is the error message I get


Object doesn't support property or method 'attr'

Answer

myid is not a valid HTML attribute. Most conventions resort to using custom attributes like this by implementing data attributes instead. For example, data-myid

<span title="cancel work" class="cancel" data-myid="111"><i class="fa fa-stop"></i> Stop work</span>

$(document).on('click','.cancel',(function(){
  alert($(this).data("myid"));
}));

Notice the changes:

  • I'm using data-myid in the span
  • I'm getting its value by using jQuery's data method.