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!