How to show / hide all tags with the same class with Java Script?

Posted by Roger on Stack Overflow See other posts from Stack Overflow or by Roger
Published on 2011-01-14T00:43:49Z Indexed on 2011/01/14 1:54 UTC
Read the original article Hit count: 530

Filed under:

I need a javascrit function that shows/hides all span tags with a specific class (t1, t2 or t3) in a HTML document. Example:

<script type="text/javascript">
<!--
    function sh(t){//show_hide(text number class)
       //???
    }
//-->
</script>

<div id='C'>
 <p>
  <span class="P">
   Normal allways visible text. 
   <span class="t1">Text 1</span> 
   <span class="t2">Text 2</span> 
   <span class="t3">Text 3</span> 
   Normal allways visible text.
  <span>
 </p>
 <p>
  <span class="P">
   Normal allways visible text. 
   <span class="t1">Text 1</span> 
   <span class="t2">Text 2</span> 
   <span class="t3">Text 3</span> 
   Normal (allways visible text.
  <span>
 </p>
 <p><span>Normal allways visible text.</span></p>
</div>

The function sh (show hide) could be trigerred like this:

<p>Show: <a href="#" onclick="sh('t1');">text 1</a> | <a href="#" onclick="sh(t2);">text 2</a> | <a href="#" onclick="sh(t3);">text 3</a></p>

An important detail is that when the span class t1 is visible, all other span class t2 and t3 are hidden. The default is to have all span class t1 visible at the first load.

Till now, the only solution I found was this one (a bit too complicated though).

Thanks a lot.


The folks are using these links to help visualize the effect of the code:

http://jsfiddle.net/v3vWM/

http://jsfiddle.net/tEUYC/

http://jsfiddle.net/RpVUN/

© Stack Overflow or respective owner

Related posts about JavaScript