bpeterson priority asked 2 years ago


Using the Bootstrap 5 Admin template and supposing one would want to update an item class in the

<nav id="sidebarMenu" class="collapse d-lg-block sidebar collapse bg-black">

to make active:

<a href="#" class="list-group-item list-group-item-action py-2 ripple">

Based on the content of the body,

What is the easiest or recommended method ?

this is working for me right now:

// Get a NodeList of certain elements
  const lgiClasses = document.querySelectorAll('a.list-group-item');
  //console.log(lgiClasses);
  const mainID = document.querySelector('main');
  //console.log(mainID.id);

  // Change the class of multiple elements with a loop
  lgiClasses.forEach(element => {
      classes-and-styles-in-the-dom
    if (element.textContent.match(mainID.id)) {
      element.classList.add('active');
    } else {
      element.classList.remove('active');
    };
  });

Grzegorz Bujański staff answered 2 years ago


We don't have any recommended way to do this. Other way I can sugest is to use window.location with a optional chaining operator:

document.querySelector(`a.active`)?.classList.remove('active');
document.querySelector(`a[href='${ window.location.href}']`)?.classList.add('active');

or

document.querySelector(`a.active`)?.classList.remove('active');
document.querySelector(`a[href='${window.location.pathname}']`)?.classList.add('active');


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Priority
  • Premium support: Yes
  • Technology: MDB Standard
  • MDB Version: MDB5 5.0.0
  • Device: any
  • Browser: Chrome
  • OS: Win10
  • Provided sample code: No
  • Provided link: No