Link to home
Start Free TrialLog in
Avatar of dlearman1
dlearman1Flag for United States of America

asked on

How is classList being used in this codepen?

I'm trying to understand the logic in this codepen https://codepen.io/tutsplus/pen/bGVPVrYand I'm confused by how classList is being used to add/remove the active class.
  1. variable menu is defined by const menu = document.querySelector(".menu");
  2.  In HTML, class .menu is applied to the top ul element
  3.  It seems to me that the code menu.classList.add("active"); is adding the class "active" to the ul element
  4. But in the codepen CSS, it appears to be added to <li class="item"> a child of menu.
I believe the ul element cannot be show/hide toggled directly, because it needs to remain displayed for non-mobile windows. I don't see that classList will recursively search children.

The codepen works so I'm missing something.
    
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

classList only applies to the referenced element.

variable menu is defined by const menu = document.querySelector(".menu");
QuerySelector will return the first element matching the selector. In this case the menu element
menu will resolve to an HTMLUListElement

So when you refer to classList on menu (menu.classList) you are talking about the classes for that specific <ul> element.
In HTML, class .menu is applied to the top ul element 
Correct
 It seems to me that the code menu.classList.add("active"); is adding the class "active" to the ul element
Correct
But in the codepen CSS, it appears to be added to <li class="item"> a child of menu.
Not seeing that. The menu toggle applies to the mobile menu - it will only kick in when the mobile menu is visible. If the mobile menu is visible you will see the 'active' class applied to it.
I don't see that classList will recursively search children.
It doesn't, applies only to the element it is called on.
Avatar of dlearman1

ASKER

Julian,
So far so good, but when I looked at the CSS to see where the show/hide was happening, I see this;

.item {
  order: 3;
  width: 100%;
  text-align: center;
  display: none;
}
.active .item {
  display: block;
}

This is what confuses me. I can see why the codepen uses .item. What I don't see how its receiving the active class.


ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial