1

I am having a really hard time understanding this. I am selecting all image tags based on whether they have the word /resize/ in the src of the img tag (I think its returning an array...?). Then I want to check each src to see if there is a file where specified in the src location of that img tag. If the image does exist, then I want to pull out that image from the array, but it won't remove. It's also saying Uncaught TypeError: images.indexOf is not a function.

Here is my code -

var images = [];
var images = $(' img[src*="/resize/"]');

console.log(images);

$.each(images, function(key, value){
    var getFile = $(value).data('src');
    $.ajax({
        type: 'HEAD',
        url: getFile,
        success: function() {
            var index = images.indexOf(key);

            if (index > -1) {
                images.splice(index, 1);
            }
        },
        error: function() {

        }
    });
    x++;
});

Can someone please help? This is killing me...

3
  • Do you know what type of images? It doesn't have indexOf method. Commented Feb 6, 2017 at 21:39
  • 1
    So at the end you want to have collection of images which doesn't have corresponding file on the server ? Commented Feb 6, 2017 at 21:46
  • Essentially yes dsfq. All of the images already exist in /files/. What I'm wanting to do is check if it doesn't exist in /resize/files/, if it doesn't then make a refactored array with all the images that have /resize/ in the src and don't yet exist in that directory, grab the oringinal image files from /files/ and run an ajax crop script, and make it exist in /resize/files. Commented Feb 6, 2017 at 21:56

1 Answer 1

1

The $ (or jQuery) constructor returns a jQuery object. jQuery objects behave much like an array with a length, slice method etc. as well as elements indexed 0, 1, 2… etc.

But a jQuery object is not a true javascript Array and does not have many of the Array methods like join, reverse or in your case indexOf.

Instead you can use the index method. Read more about it on jQuery API Documentation

Sign up to request clarification or add additional context in comments.

1 Comment

It is not an Array no, as I said it behaves like one, and you can actually call Array methods on a jQuery object (Array.prototype.forEach.call(y => console.log(y))). You actually quite often meet array-like objects. When you use document.querySelectorAll a NodeList is returned which does not have array methods. Doing Array.prototype.slice.call(nodeList, 0) return it as a true array (on which we can then map, filter, reduce etc) EDIT: Seems like the guy I commented to has deleted his comment, but I'll leave this here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.