-1

I'm trying to set an 'active' class on whichever 'nav-link' element is clicked. Hopefully this will persist to the next page where it takes the user.

Currently I am seeing sidebar.getElementsByClassName is not a function in the console. I guess I cannot get all the elements of a class inside another class?

    <div class="sidebar">
      <div class="logo"><a href="{% url 'main:dashboard_view' %}" class="simple-text logo-normal">
          <img src="{% static 'img/logos/logo-white.png' %}" class="img-fluid">
        </a></div>
      <div class="sidebar-wrapper">
        <ul class="nav">
          <li class="nav-item active  ">
            <a class="nav-link" href="{% url 'main:dashboard_view' %}">
              <i class="material-icons">dashboard</i>
              <p>Dashboard</p>
            </a>
          </li>
          <li class="nav-item ">
            <a class="nav-link" href="{% url 'main:dashboard_profile_view' %}">
              <i class="material-icons">person</i>
              <p>{{user.username}}</p>
            </a>
          </li>

          <li class="nav-item ">
            <a class="nav-link" href="{% url 'main:create_blog_post_view' %}">
              <i class="material-icons">library_books</i>
              <p>Blog</p>
            </a>
          </li>
           ....
        </ul>
      </div>
    </div>

  <script>
// Get the container element
var sidebar = document.getElementsByClassName("sidebar");

// Get all buttons with class="nav-link" inside the container
var navLinks = sidebar.getElementsByClassName("nav-link");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < navLinks.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
} 
  </script>
GTA.sprx
  • 817
  • 1
  • 8
  • 24
  • Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Sebastian Simon May 09 '20 at 04:50

1 Answers1

-1

getElementsByClassName return an array of elemnets. It is the right code : var navLinks = sidebar[0].getElementsByClassName("nav-link");

Ahmad Hamzavi
  • 626
  • 6
  • 18