Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Does anyone know why my onclick event is returning null?

I'm trying to create drop down menu all in vanilla js and I cant figure out why the onclick function isnt working

<!DOCTYPE HTML>
<html>
 <head>
  <title>Store | Home</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <link rel="stylesheet" href="css/main.css">
  <meta name="viewport" content="width=device-width" initial-scale="1.0">
 </head>
 <body>
  <header>
   <h1 class="main-header-title"> Store</h1>
   <nav>
    <ul>
     <li id="homeTab"><a href="index.html">Home</a></li>
     <li id="clothesTab"><a href="clothes.html">Clothes</a></li>
    </ul>
   </nav>
  </header>
  <section>
  </section>
  <footer>
   <ul>
     <li></li>
     <li></li>
     <li><a href="contact.html">Contact</a></li>
 </footer>
 <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
 <script scr="js/main.js"></script>
 </body>
</html>
var header= document.getElementsByTagName('header')[0];
var nav=header.children[1].children[0];
var clothesTab= getId(clothesTab);

function getId(id){
            var element= document.getElementById(id);
            return element;
               }

function subUl(itemNum){                //creates unordered list that will be appended to the main one
            var subUl=document.createElement('ul');
                        for(i=0; i<itemNum; i++){
                var li=document.createElement('li');
                subUl.appendChild(li);
            }
            return subUl;
}
function displayDropMenu(navItem,num){

                    navItem.onclick=function(){navItem.appendChild(subUl(num));};
}           

displayDropMenu(clothesTab,2);

Please post a workspace snapshot, or post the rest of your code, including html. That will make it much easier to trouble shoot and help you figure out what might be going wrong.

1 Answer

document.getElementById is expecting a string so you could change your clothesTab variable to fix this problem:

var clothesTab = getId('clothesTab'); // <-- changed to a string

also, you probably already fixed it but your script tag has a typo ( "scr" instead of "src").