1

I'm trying to do something deceptively simple -- adding a class to the active backbone element. The code I want to use is:

 this.$el.addClass('classIWant');

However, this doesn't work all the time. Sometimes it seems to, but not all the time. However, this always works.

 var id = this.$el.attr('id');

 $('#' + id).addClass('classIWant');

Obviously I don't want the second example, as it relies so heavily on HTML and the DOM. Is there any reason why the first shouldn't work, or am I missing something else?

streetlight
  • 5,968
  • 13
  • 62
  • 101

2 Answers2

1

Seems this points to something wrong. If you are running this code in function myFunc, then just add to initialize next line:

_.bindAll(this, 'myFunc');

And got with you first approach, this.$el.addClass('classYouWant').

Artem Volkhin
  • 1,362
  • 8
  • 22
0

This code should work:

this.$el.addClass('classIWant');

but only if it is present within your onRender() function or any functions that are called after onRender() is. If you have this code in your initialize function then it will not work as the dom for that view has not yet been generated

Scott
  • 469
  • 5
  • 11