Can't remove class with Javascript

New Member
4 0 0

I'm trying to remove a class attribute from my code using Javascript but I get an error saying "TypeError: Cannot read property 'remove' of undefined"

const dropDowns = document.querySelectorAll(".mobile-nav .dropdown");
for (var i = 0; i < dropDowns.length; i++) {
  dropDowns[i].addEventListener("click", function () {

function closeDropDown() {
  const temp = document.querySelectorAll(".mobile-nav .dropdown-content");


<div class="dropdown">
          <button class="dropbtn">{{ link.title }}
            <i class="fa fa-caret-down"></i>
          <div class="dropdown-content">
            <div class="mm-row">
              <div class="mm-column">
                <div class="mm-subcategory">
                  <i class="fas fa-arrow-left" onclick="closeDropDown()"></i>
                  <h3>{{ link.title | link_to: link.url }}</h3>
                {% for child_link in linklists[child_list_handle].links %}
                {{ child_link.title | link_to: child_link.url }}
                {% endfor %}
              <div class="dropdown-feature">
                {% assign collection= collections.winter-wear %}
                <img src="{{ collection.image | img_url: '908x330' }}" >
          </div><!-- /dropdown-content -->


Reply 1 (1)

Shopify Partner
284 42 89


You are getting this error because temp is not defined, '.mobile-nav .dropdown-content' html elements have not been found.

You need to check if this element exists before remove the class. An example is to do something like this in your code.

function closeDropDown() {
  const temp = document.querySelectorAll(".mobile-nav .dropdown-content");
  typeof(temp) !== "undefined" && temp.classList.remove("active");