-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>
CalAlt
  • 1,683
  • 2
  • 15
  • 29
  • did you forget to add `projectImage.children().forEach()`..? – Jimenemex Dec 28 '17 at 17:26
  • Possible duplicate of [How to convert a DOM node list to an array in Javascript?](https://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript) – Dexygen Dec 28 '17 at 17:28

3 Answers3

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I swear you are one second ahead of me the last couple of days. For posterity the documentation specifically can be found -> http://api.jquery.com/jquery.each/ – zfrisch Dec 28 '17 at 17:29
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.

palaѕн
  • 72,112
  • 17
  • 116
  • 136
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'); });
samanime
  • 25,408
  • 15
  • 90
  • 139