Jon Biz
Jon Biz

Reputation: 1003

.bind to dom objects within .each loop

I am iterating over DOM elements using each but when the elements are made available inside the .each loop, they will not accept jQuery bind events.

$('#products .page_item').mouseover(function(){
   console.log('this works, adding the mouseover to every selected element');
});

$('#products .page_item').each(function(index, element){
    element.mouseover(function(){
        console.log("this throws 'not a function'");
    });
});

How do I make each element available within the .each loop so I can bind events to them?

(I am iterating over the elements in this manner so I can conditionally exclude some of the elements from the bind, FWIW.)

Upvotes: 2

Views: 1728

Answers (2)

Logan
Logan

Reputation: 1694

Try this code :

$('#products .page_item').mouseover(function(){
   console.log('this works, adding the mouseover to every selected element');
});

$('#products .page_item').each(function(index, element){
    $(element).mouseover(function(){
        console.log("this throws 'not a function'");
    });
});

Upvotes: 0

gdoron
gdoron

Reputation: 150253

You need to wrap element in jQuery object:

$(element).mouseover(function(){

element (or this) is the DOM element, not the jQuery object.

Full code fixed:

$('#products .page_item').each(function(index, element){
    $(element).mouseover(function(){
        console.log("This works!");
    });
});

From the each docs:

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

Upvotes: 4

Related Questions