Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting better JS
    text
    copied!<p>I'm trying to see how I can write plain javascript that would do the same thing that I can do in jquery.</p> <p>I wrote this for hide/show sub navigation:</p> <pre><code>var i = 0; var header = document.querySelector( 'header' ).childNodes; for( i; i&lt;=header.length-1; i++ ){ if( header[i].tagName !== undefined ){ var nav = header[i].childNodes; for( i=0; i&lt;=nav.length-1; i++ ){ if( nav[i].tagName !== undefined ){ if( nav[i].tagName === "MENU" ){ nav[i].className = "hide"; } else { nav[i].onclick = function(){ var dest = this.attributes.href.nodeValue; for( i=0; i&lt;=nav.length-1; i++ ){ if( nav[i].className === "show" ) nav[i].className = "hide"; } document.getElementById( dest.replace( "#", "" ) ).className = "show"; } } } } } } </code></pre> <p>html is:</p> <pre><code>&lt;body&gt; &lt;header&gt; &lt;nav&gt; &lt;a href="#home"&gt;Home&lt;/a&gt; &lt;a href="#work"&gt;Work&lt;/a&gt; &lt;a href="#contact"&gt;Contact&lt;/a&gt; &lt;menu id="home"&gt; &lt;a href="#"&gt;About&lt;/a&gt; &lt;a href="#"&gt;Mission&lt;/a&gt; &lt;a href="#"&gt;Blog&lt;/a&gt; &lt;/menu&gt; &lt;menu id="work"&gt; &lt;a href="#"&gt;Web&lt;/a&gt; &lt;a href="#"&gt;Print&lt;/a&gt; &lt;a href="#"&gt;Media&lt;/a&gt; &lt;/menu&gt; &lt;menu id="contact"&gt; &lt;a href="#"&gt;Info&lt;/a&gt; &lt;a href="#"&gt;Sales&lt;/a&gt; &lt;a href="#"&gt;Support&lt;/a&gt; &lt;/menu&gt; &lt;/nav&gt; &lt;/header&gt; &lt;/body&gt; </code></pre> <p>with some css to display:none or display:block for .hide/.show</p> <p>My question would be "is there a better way?"</p> <p>Also, when I try to move the function outside of .onclick, I can't use "this" as variable.</p> <pre><code>nav[i].onclick = showHide( nav ); function showHide( el ){ var dest = this.attributes.href.nodeValue; for( i=0; i&lt;=el.length-1; i++ ){ if( el[i].className === "show" ) el[i].className = "hide"; } document.getElementById( dest.replace( "#", "" ) ).className = "show"; } </code></pre> <p>How can I pass the variable of the element being clicked on as "this"?</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