3

I have an ul with up to 3 possible li's inside (meaning it can have 1, 2 or 3). All 3, when clicked, open a modal and get an class="active".

My goal is to remove that class when you close the modal using the X button on the top right corner.

This is the the portion of code inside the ul :

    {% for key, data in resources %}
        <li{% if loop.first %} ng-class="class" {% verbatim %}{{class}}{% endverbatim %} {% endif %} id="icon-resource">
            <a
                data-toggle="tab"
                href="#{{ key }}"
                segment-event="Modules: Tutor: Clicked {{ key|capitalize }} Section"
                segment-not-track-if-class="active"
                onclick="openAssistance()"
                ng-click="changeClass()"
            >
                <i class="icon-{{ key }} icon-sm"></i>
                <span class="sr-only">{{ ('resources.tabs.' ~ key ~ '.title') | trans }}</span>
            </a>
        </li>
    {% endfor %}

And this is the X button:

  <button type="button" class="close" toggle-class="oc-open" onclick="closeAssistance()" aria-hidden="true">&times;</button>

This is the js I made to close the modal and remove the active class:

function openAssistance() {
  var x = document.getElementById('assistance');
  if (x.style.display === "none") {
      x.style.display = "block";
  }
}

function closeAssistance() {
  var x = document.getElementById('assistance');
  if (x.style.display === "block") {
      x.style.display = "none";
  }
  document.getElementById("icon-resource").classList.remove('active');
}

The problem is: it only removes the active class of the first icon, meaning that if you close the modal with the second or third icon active, it stays active.

I was hoping for an angularjs solution rather than a pure js like mine, but I'll be happy with either options.

1 Answer 1

2

Instead of getElementById use querySelectorAll like that:

document.querySelectorAll("#icon-resource").forEach(function (li) {
    li.classList.remove("active");
});

But I suggest you to use a class instead of an ID because, at least in theory, IDs should be unique.

Sign up to request clarification or add additional context in comments.

3 Comments

Worked like a charm, thanks! Care to explain the difference?
getElementById takes only the first occurrence from top to bottom of the document and returns the node, instead querySelectorAll returns an array with all nodes that matches with selector.
Oww I see! Thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.