3

I have this error in Jquery when I try to each an array of HTML elements and handle onclick of that element.

Object.keys(collapsibles).forEach(function (key){
            $(collapsibles[key]).on('click' , function( e ) {
                e.preventDefault();
                const id = $(this).data("id");
                if (id !== _that.currentId) {
                    _that.closeCurrentOpen();
                    $(`[data-target="${$(this).data("id")}"]`).slideDown().addClass('open');
                    $(`[data-img="${$(this).data("id")}"]`).slideDown().addClass('arrowOpened');
                    return _that.currentId = id;
                } else {
                    return _that.closeCurrentOpen();
                }
            });
        });

The error is appear in this line

$(collapsibles[key]).on('click' , function( e ) {

Collapsibles value

var collapsibles = $('[data-behavior="collapsible"]');
Santiago D'Antuoni
  • 164
  • 1
  • 2
  • 13

2 Answers2

3

Code below has makes error because $(collapsibles[key]) is not a jQuery object:

$(collapsibles[key]).on('click' , function( e ) {//...});

Please see this fiddle. I simulated your code in that. You can see collapsibles in console that seems you didn't think it's a array that it's not suitable for you.

You can use this code instead (jsFiddle):

$.each(collapsibles, function() {
  $(this).on('click', function() {
   // ...
  });
});
Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
0

Uh, var collapsibles = $('[data-behavior="collapsible"]'); is not an array but rather a jQuery collection object. And you should not iterate array-like objects like that, neither with for … in nor with Object.keys(…).forEach.

For jQuery collections, just use .each, or don't use it at all but just call the .on method on it directly which will install the listener on all of the selected elements.

var collapsibles = $('[data-behavior="collapsible"]');
collapsibles.each(function() {
    $(this).on('click', function(e) {
        e.preventDefault();
        const id = $(this).data("id");
        if (id !== _that.currentId) {
            _that.closeCurrentOpen();
            $(`[data-target="${$(this).data("id")}"]`).slideDown().addClass('open');
            $(`[data-img="${$(this).data("id")}"]`).slideDown().addClass('arrowOpened');
            return _that.currentId = id;
        } else {
            return _that.closeCurrentOpen();
        }
    });
});

var collapsibles = $('[data-behavior="collapsible"]');
collapsibles.on('click', function(e) {
    e.preventDefault();
    const id = $(this).data("id");
    if (id !== _that.currentId) {
        _that.closeCurrentOpen();
        $(`[data-target="${$(this).data("id")}"]`).slideDown().addClass('open');
        $(`[data-img="${$(this).data("id")}"]`).slideDown().addClass('arrowOpened');
        return _that.currentId = id;
    } else {
        return _that.closeCurrentOpen();
    }
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375