Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As not all browsers support the all methods (e.g. IE does not support <code>getElementsByClassName</code>, I suggest to use a library like <a href="http://jquery.com/" rel="nofollow">jQuery</a> that makes cross-browser DOM access very easy.</p> <p>But luckily, <code>getElementsByTagName</code> is <a href="http://www.quirksmode.org/dom/w3c_core.html#t12" rel="nofollow">supported by all browsers</a>, so you could do:</p> <pre><code>var spans = document.getElementsByTagName('span'); function sh(cls) { for (var i = spans.length; i--;) { var element = spans[i]; if (element.className.match(RegExp('\\b' + cls + '\\b'))) { element.style.display = (element.style.display === 'none') ? '' : 'none'; } } } </code></pre> <p>I don't know which spans you want to hide or show, so I just assume you are going to toggle the visibility of one group. If you are going to get the span elements only once like I did, then you have to put the script <em>after</em> the content (before the closing <code>&lt;body&gt;</code> tag). Otherwise the span element won't be found.</p> <p><a href="http://jsfiddle.net/Xr7yM/" rel="nofollow"><strong>DEMO</strong></a></p> <hr> <p>If supported, using <a href="https://developer.mozilla.org/En/DOM/document.querySelectorAll" rel="nofollow"><code>document.querySelectorAll</code></a> might be even better. You could do:</p> <pre><code>window.sh = (function() { function toggleVisibility(element) { element.style.display = (element.style.display === 'none') ? '' : 'none'; } if(typeof document.querySelectorAll === 'function') { return function(cls) { var spans = document.querySelectorAll('span.' + cls); for (var i = spans.length; i--;) { toggleVisibility(spans[i]); } }; } else { var spans = document.getElementsByTagName('span'); return function(cls) { for (var i = spans.length; i--;) { var element = spans[i]; if (element.className.match(RegExp('\\b' + cls + '\\b'))) { toggleVisibility(element); } } }; } }()); </code></pre> <p>This checks once whether <code>querySelectorAll</code> is supported creates an appropriate <code>sh</code> function.</p> <p><a href="http://jsfiddle.net/Xr7yM/2/" rel="nofollow"><strong>DEMO 2</strong></a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload