2

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.)

2 Answers 2

4

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.

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

Comments

0

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'");
    });
});

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.