Object [object HTMLAnchorElement] does not have 'attr' method

advertisements

I'm examining a DOM element using console.log. The DOM element is an anchor:

 <a href="#" class="videoimage" data-id="ks3H_s3e-Wc"></a>

When I try to access its id and output it using either of the following lines:

console.log($this.attr(data-id));

or

console.log($this.data('id'));

I get an error:

Object [object HTMLAnchorElement] has no method 'attr'

('data' in the second case)

Does an anchor element not have the attr or data methods, or is my mistake something else?


That looks like its because your this reference is not a jquery object. Try these instead:

$(this).data('id')
$(this).attr('data-id')