Home > Software design >  Active menu item NOT based on URL but based on a variable
Active menu item NOT based on URL but based on a variable

Time:12-12

I want to have a Menu with active items on my website. It should be added a class to activate the item. Since the project has cryptic URLs, URL-based solutions are not possible. The text of the respective menu item is shown in the respective page title.

My idea was to compare the pagetitle id="navtopheader" with the text in the menu item. If it is equal, add the menuactive class to the respective menu item.

My HTML looks basically like this:

<div id="navtopheader" >menu item 1</div>
...
<div >
   <p>menu item 1</p>
</div>
<div >
   <p>menu item 2</p>
</div>
...

I can do it actually in an inefficient way:

var headertext = document.getElementById("navtopheader").innerText

var menutext0 = document.getElementsByClassName("nav_ebene_2")[0].innerText
var navlist = document.getElementsByClassName("nav_ebene_2");
if (headertext == menutext0) {
    navlist[0].classList.add("activemenu");
}

var menuitem1 = document.getElementsByClassName("nav_ebene_2")[1].innerText
if (headertext == menuitem1) {
    navlist[1].classList.add("activemenu");
}
...

But since the number of menu items varies across the website, i would get an error message if i include too much/too few menu items.

Is there an appropriate solution? I tried the whole day but didn't solve the problem. Thank you!

CodePudding user response:

Iterate over the collection of <p>s that are children of nav_ebene_2. When a match is found, add the class to its parent.

const headerText = document.querySelector('#navtopheader').textContent;
for (const p of document.querySelectorAll('.nav_ebene_2 p')) {
  if (p.textContent === headerText) {
    p.parentElement.classList.add('activemenu');
  }
}
  • Related