-1

I have array elements, I would like to apply a function to each element in this array that adds the class .active to the first child. Currently I'm getting the error

'Uncaught TypeError: projectImage.forEach is not a function'

What is the problem with this? Any help pointers be greatly appreciated

var Image = {
    init: function() {
        Image.setupImages();
    },
    setupImages: function() {
        var projectImage = $('.project-img');
        projectImage.forEach(function(project) {
            project.find('.project-thumnbail').eq(0).addClass('active');
        });
    },
}
$(document).ready(function() {
    Image.init();
});
.project-thumbnail {
    visibility: hidden;
}
.active {
    visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="project-img">
    <div class="project-thumbnail">
        <img src="http://via.placeholder.com/250/000000">
    </div>
    <div class="project-thumbnail">
        <img src="http://via.placeholder.com/250/000000">
    </div>
    <div class="project-thumbnail">
        <img src="http://via.placeholder.com/250/000000">
    </div>
    <div class="project-thumbnail">
        <img src="http://via.placeholder.com/250/000000">
    </div>
</div>

<div class="project-img">
    <div class="project-thumbnail">
        <img src="http://via.placeholder.com/250/ffffff/000000">
    </div>
    <div class="project-thumbnail">
        <img src="http://via.placeholder.com/250/ffffff/000000">
    </div>
</div>

2

3 Answers 3

3

As the error is trying to tell you, jQuery doesn't have a forEach function.

You probably mean .each().
Also, it passes elements, not jQuery objects.

See the documentation.

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

1 Comment

I swear you are one second ahead of me the last couple of days. For posterity the documentation specifically can be found -> api.jquery.com/jquery.each
1

Replace forEach with .each() like:

var projectImage = $('.project-img');
projectImage.each(function() {
    $(this).find('project-thumnbail:eq(0)').addClass('active');
});

as projectImage is an jQuery object not an JS array and forEach is an array method.

Comments

0
var projectImage = $('.project-img');

gives a jQuery object. forEach() isn't a function on the jQuery object, it's only on vanilla.

Instead of forEach(), use each(), which is the jQuery equivalent.

projectImage.each(element => { console.log('do something'); });

Comments

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.