Rob Gaudet
Rob Gaudet

Reputation: 131

jquery inArray always returns false, array created from jquery.get()

I'm getting all images that are inside of a div.

var favImages = $('#divPlacesILove img').get();

I'm checking to see of the tagImage element is inside of the array.

This always returns -1, when it should not.

alert($.inArray($(tagImage).attr('src'), favImages));

Upvotes: 0

Views: 605

Answers (3)

Rajat Singhal
Rajat Singhal

Reputation: 11264

what is there in array is DOM elements, and you are comparing against href!!

You can try this, if you insist on using same set of functions..

var favImages = $('#divPlacesILove img').get();
alert($.inArray($(tagImage)[0], favImages));

Now favImages is array of images, and $(tagImage)[0] is your taggeed image..

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227280

$('#divPlacesILove img').get()

This returns you an array of DOM elements.

$.inArray($(tagImage).attr('src'), favImages))

You are looking for a string in an array of DOM elements, so it won't find anything.

Why are you using inArray here? If you want to see if the jQuery object contains an element use, .is:

$('#divPlacesILove img').is(tagImage); // true

Or .filter:

$('#divPlacesILove img').filter(function(){
    return this === tagImage; // or $(this).prop('src') === $(tagImage).prop('src')
})

Upvotes: 2

David Hellsing
David Hellsing

Reputation: 108500

You are probably looking for .map():

var favImages = $('#divPlacesILove img').map(function() {
    return this.src;
}).get();

Now favImages will be an array of src attributes.

Upvotes: 2

Related Questions