Brand
Brand

Reputation: 1701

"<HTMLImageElement> has no method" error for an object that appears to exist

I'm using Chrome and the build in developer tools. What I do the following in the console

$('.votes > a > img')[0]

I get this

<img src="/myimage_png">

But if I do

$('.votes > a > img')[0].get(0).tagName

I get

TypeError: Object #<HTMLImageElement> has no method 'get'

I don't understand why sometimes I'm able to do .get(0).tagName and sometimes I'm not (depending on what my selector is of course)

Upvotes: 2

Views: 4580

Answers (2)

Marc B
Marc B

Reputation: 360702

.get() retrieves a specified DOM element from a list of elements. the $('.votes ...') stuff call returns such an element list. You dereference this list with [0], fetching the first of the found nodes. That means you're no longer working with a DOMNode list, you're working with a DOMElement, and a DOMElement has no .get() method.

Upvotes: 5

Aaron Powell
Aaron Powell

Reputation: 25097

The numberical indexer of a jQuery object (using [0]) will return the DOM element that is at that position in the jQuery results array.

In your example of

$('.votes > a > img')[0].get(0).tagName

What you're doing is using the indexer to get back the DOM element then attempting to use the get method against it.

Using the indexer or get will result in the same thing as they both return the DOM element at a particular point in the jQuery results array (the only main difference is get() with no arguments returns only the DOM elements).

Upvotes: 2

Related Questions