views:

33

answers:

2

I would like to toggle (hide/show) several elements of my web page.

All those elements are in between this tag:

 <div class="class_name">to toggle</div> 
 <div class="class_name">to toggle2</div> 

I would like to use javascript to toggle all the elements with class=class_name when the user clicks on a button.

So far all the code I found only hides div by ID.

I am working with ruby on rails, so if there is a way not to write the js code and not create new functions I would appreciate. I would also like a way to call visual effects but on class and not id.

Thanks.

+3  A: 

You can use jQuery:

$('.class_name').toggle();
SLaks
Almost tempted to downvote for suggesting jQuery when the question mentions nothing about it, but doing *anything* by class name in JS is *so* painful.
meagar
Thanks, it's actually working, but in my case the div's are in a table, and weirdly it does not apply to them. Any clue on how I could have that working?
jules
This code will work for any elements with that class, anywhere. Check the class name
SLaks
It does not seem to work in that case: <table><tr><div class="contract_row" ><td> hello</td></div></tr></table>
jules
That's invalid HTML; the `<div>` must be inside the table cell. The DOM parser will attempt to make it sane and end up putting the `<div>` outside the table with no children.
SLaks
So if I understand well, the only way to hide a row is to hide every single cell of it?
jules
You can hide the `<tr>` itself. For example: `$('.someClass').parent()` or `$('tr:has(.someCLass)')`. See the [documentation](http://api.jquery.com/category/selectors/).
SLaks
Thanks so much!
jules
+1  A: 

Rails comes with prototype library out of the box. All you have to do to use it is add this line in <head> part of your layout:

<%= javascript_include_tag :defaults %>

Then you can use this call to toggle elements by class name:

$$('.class_name').each(Element.toggle);
Matt