Changing class of DOM object in RJS

Hey, in an RJS file, what is the most effecient way to set the
className of an dom element?

is there some page.replace_class or such?

I am new to ruby on rails, so sorry if this is a dumb question.

Thanks!

Kelvin Jones wrote:

Hey, in an RJS file, what is the most effecient way to set the
className of an dom element?

is there some page.replace_class or such?

   page['element'].className = 'class'

render :update do |page|
  page << "$('element_id').className = 'new-class'"
end

or

render :update do |page|
  page << "new Element.ClassNames('element_id').set('new-class')"
end

Element.ClassNames also has add() and remove() methods.

What is the difference between those two techniques? Which would I want
to use when? I dont quite understand what is going on in Chris Hall's
technique, could someone explain?

Thank you!

Mark showed only the main part of javascript generation

page['element'].className = 'class'

This code can be put in RJS template and it will work).
Chris used more explicit form:

render :update do |page|
   page << "$('element_id').className = 'class'"
end

Which can be used in controller's action code. In fact, those two produce
equal results. RJS templates are implicitly wrapped in "render :update"
block.

Also, Mark has showed the use of page element proxy while Chris just generate
all the code himself. Personally I would prefer using element proxies.

Also, Chris has showed the use of Element.ClassNames class from Prototype
library (that is shipped with Rails). It allows to add / remove individual
classes (e.g. If you have several class names assigned to element, you can
remove or add one without interfering the others). It's useful when you need
e.g. mark some element as "selected" or remove such mark.
But, there is a more Rails-natural way to make use of Element.ClassNames
class. In prototype, if you call .classNames() on DOM element, it will return
the appropriate Element.ClassNames instance wrapped around that element. So
you could just do (in javascript):
    $('my_element_id').classNames().add('selected')
or
    $('my_element_id').classNames().remove('selected')

So, because of this nice feature of Prototype, you can continue using element
proxies to do all the stuff (in RJS template):

    page['my_element_id'].classNames.add('selected')
or
    page['my_element_id'].classNames.remove('selected')

I hope now you have a better understanding of what is going on in RJS.

Thank you Maxim, very useful explanation. Also thanks Mark and Chris
for the prompt answers!

Kel