Tyler P.
Tyler P.

Reputation: 23

Can't run Jquery methods inside Template.onRendered?

Sorry if this question may sound stupid but I'm getting an error that I can't make sense of. I have the following code in onRendered:

Template.displayItem.onRendered(function(){
  if ($('div.item')[0]) {
    console.log('First item found!');
    $('div.item')[0].hide();
  }
});

Now I can see the correct output "First item found!" in the console - this means Jquery selector is working and it found the element in the DOM, but the .hide() Jquery method was not executed and I'm getting the error message below:

Exception from Tracker afterFlush function:
TypeError: $(...)[0].hide is not a function

I'm not sure what causes this behavior. Has anyone encountered similar error(s)?

Upvotes: 0

Views: 89

Answers (3)

corvid
corvid

Reputation: 11187

Your error is because $('div.hide')[0] is a plain node, and not a jquery object.

You should probably use this.$('div.hide').first().hide()

Upvotes: 0

SO is full of Monkeys
SO is full of Monkeys

Reputation: 319

use $(this).hide()

  if ($('div.item')[0]) {
    console.log('First item found!');
     $(this).hide()
  }

Upvotes: 0

David Weldon
David Weldon

Reputation: 64312

Try $('div.item').first().hide() instead. The array returned by your selector will contain DOM objects which don't have jQuery methods (like hide) attached to them. In contrast, first will return a proper jQuery object.

Upvotes: 2

Related Questions