keram
keram

Reputation: 2421

Expecting HTMLImageElement but getting simple Object when iterating over jQuery list of img tags

I am gather imgs:

container.find('img')

Log says this is (console.log('img '+imgs[0]))

[object HTMLImageElement]

But when I iterating over this list with each():

            container.find('img').each(function(idx) {
                var curr = $(this);
                                    console.log('curr ' + curr);

        });

I am getting:

[object Object]

I think it is reason of my anotger problem of checking existance in array:

        if (! jQuery.inArray(curr, hiddenImgs)) {
              hiddenImgs.push(curr);
            }

And even that I am sure that element is no in array I am getting FALSE :/

It's crazy. Could someone help?

Upvotes: 2

Views: 1917

Answers (3)

Moin Zaman
Moin Zaman

Reputation: 25455

inside the .each() try:

console.log('curr ' + curr.get(0));

Upvotes: 0

M Abbas
M Abbas

Reputation: 6479

You are getting [object Object] because when you called $(this) in your function, you created a new jQuery object that references the image element, and the type of a jquery object is an object and not HTMLImageElement. See jQuery( selector [, context] )

The function inArray returns -1 and not 0 when it doesn't find a match, so you have to change your code to:

if (jQuery.inArray(curr, hiddenImgs) == -1) {
              hiddenImgs.push(curr);
            }

See jQuery.inArray()

Upvotes: 1

Esailija
Esailija

Reputation: 140230

First of all, to get useful log result, just log it directly instead of converting it to a string:

Examples:

console.log( imgs[0] );
console.log( curr );

Secondly, in the first case you are logging the Image element and in the second case you are logging a jQuery object:

$(this) //<-- return a jQuery object wrapping `this`, the original element is in $(this)[0]
this //<-- plain this, it's the dom element itself. I.E. HTMLImageElement

Upvotes: 3

Related Questions