Jquery .each in Meteor?


#1

Having a small issue that I’m sure is easy to resolve. Basically I’m trying to get this code to work in Meteor:

$('.new').each(function(i) {
            $(i).removeClass('new');
        });

It seems the “each” function doesn’t work in Meteor.

Any advice please?

Thanks!


#2

I’d first make sure this isn’t running on the server side. Then I’d put a breakpoint in devtools on the first line and try to run it in the console.


#3

Definitely not running on server side. It’s doing nothing at all.

When I run the command in console, it’s not removing the class, but it’s notifying me of each object that has the class, as if I did a find() event on them.


#4

Do this $('.new').removeClass('new');


#5

That worked… Thanks!

Should have known it was something silly… I tried so many with the .each and didn’t even need it!


#6

As any other jQuery function, .each is working on Meteor, except that you need to make sure it runs when the DOM is actually ready with what you want to .each over. It is a very common misconception putting jQuery in .onRendered callback and assuming that the DOM is all the way rendered. Reactivity might actually foil your plan a little bit.


#7

jamgold,

This was actually an event, so everything was rendered. But the each wasnt necessary after all!

Thanks a lot guys!


#8

Even in event callbacks there is a misconception about how to use jQuery. In Blaze an event callback receives the event and template the event occurred in. Every Blaze template has its own template.$ jQuery that will scope it to the DOM of the template.

The issue can be that child templates inherit the parent events, muddling the concept of the template DOM a little. That is at least my experience.


#9

First, as @mordrax mentions, you don’t need .each for this.

$('.new').removeClass('new')

is the same as your example.

Second, use this instead of i, like this:

$('.new').each(function() {
    $(this).removeClass('new');
});

#10

Exactly, this issue doesn’t have anything to do with Meteor.

$('.new').each(callback) passes index as the first argument to the callback rather than the matched element. The jQuery docs describe it clearly here: https://api.jquery.com/each/


#11

When you think that your code is right but now working then check chrome developers tools’s console window for any errors.

Alternately in you jQuery Each code you can put alert and this will tell you how many times it is looping, like this:

$(’.new’).each(function(i) {
alert(‘hi’)
});