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

Fernando Jimenez
PLUS
Fernando Jimenez
Courses Plus Student 8,455 Points

Why is this simple variable wrong?

const stickyMenuPhone = document.querySelector(".hmenu_social_holder.hmenu_hide_for_mobile"); //Select  class

alert('Hello World');

That class belongs to this index page https://advocatesidaho.staging.wpengine.com/

all I am trying to do is to just assign that value to stickyMenuPhone but it returns null instead.

1 Answer

Tim Knight
Tim Knight
28,888 Points

Fernando,

I'm going to guess that your JavaScript is executing before your DOM is fully loaded here so the item with the class is coming back as null. To prevent that I'd just put your code inside of an iife like this:

(function () {
  const stickyMenuPhone = document.querySelector('div.hmenu_social_holder .hmenu_hide_for_mobile');
  console.log('stickyMenuPhone');
})();

That way it'll run once everything is loaded.