M. V.
M. V.

Reputation: 15

Active menu item NOT based on URL but based on a variable

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" class="navtopheader">menu item 1</div>
...
<div class="nav_ebene_2">
   <p>menu item 1</p>
</div>
<div class="nav_ebene_2">
   <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!

Upvotes: 0

Views: 51

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

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');
  }
}

Upvotes: 2

Related Questions