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
Nikos Papapetrou
6,305 PointsHello! What am I doing wrong> "addEventListener is not function" https://codepen.io/nikospapapetrou/pen/gOPrzWB
Hello! I am trying to create a responsive menu for mobile devices. I watched the DOM course and I try to create something like the lecture 4 in "Making Changes to the DOM". But it throw me: "Uncaught TypeError: menuButton.addEventListener is not a function" https://codepen.io/nikospapapetrou/pen/gOPrzWB If someone can explain me my mistake I will appreciate it.
5 Answers
Steven Parker
243,201 PointsThe "menuButton" is an HTMLCollection, which has no "addEventListener" method. You probably want it to refer to the element, which can be selected by indexing the collection:
const menuButton = document.getElementsByClassName("menuButton")[0]; // select element
You'll have a similar issue with the code in the handler, since "nav_items" is also a collection. Perhaps you meant to use the "nav" element there instead?
Nikos Papapetrou
6,305 PointsSo if I add an Id will work? I will experiment.
Steven Parker
243,201 PointsYes, and another option is using the "querySelector" function with the class:
const menuButton = document.querySelector(".menuButton"); // select only the first element
Nikos Papapetrou
6,305 PointsOk it doesn't work. main.js:4 Uncaught TypeError: Cannot read property 'addEventListener' of null at main.js:4. I will figure it out.
Steven Parker
243,201 PointsOdd, your new codepen works for me. No error, and when I click the button the menu items go away.
But also note that in the "if" clause there is an assignment instead of a comparison.
Nikos Papapetrou
6,305 PointsYes the menu disappear but it don't reappear in the next click. Like a hamburger menu.
Steven Parker
243,201 PointsThey don't reappear because of the assignment ("=") instead of a comparison ("==").
Nikos Papapetrou
6,305 PointsYes, you are right, it seems to be closer now. Thank you very much Steven!
Nikos Papapetrou
6,305 PointsNikos Papapetrou
6,305 PointsThank you Steven. It is a little confusing I will search it further for Html collections. All methods "getElementBy*" returns a live collection. I thought with this way I had chosen the element ul.
Steven Parker
243,201 PointsSteven Parker
243,201 PointsThe "GetElement‍s..." (plural) functions return a collection. The "GetElementById" (singular) returns one element.