M. V.
M. V.

Reputation: 15

Active menu item based on URL and ID

I want to have active menu items in my navigation based on URL and ID, not href. None of the available solutions (this one, this one , or this one) worked for me.

My Navigation looks like this

<nav id="PageNavigation">
    <div class="nav_ebene_2">
        <div role="button" class="nav-item" id="P_Bogendaten.aspx?IDNavi=194">
            <p>menu item 1</p>
        </div>
    </div>
</nav>

The URL, if clicked on menu item 1, is https://example.de/App_AspxFiles/P_Bogendaten.aspx?IDNavi=194. I want to add the class menuactive to the parent element (div which includes nav_ebene_2)

I need to compare the id with the current url, if it matches, add menuactive. This would be my way, but the if conditions is never true.

  var currenturl  = window.location.href
  for (const div of document.querySelectorAll("#PageNavigation nav-item")) {
    if (div.id == currenturl ) {
      div.parentElement.classList.add("activemenu");
    }
  }

Thank you very much!

Upvotes: 1

Views: 987

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

If you read the URI from the window.location

const params = new URLSearchParams(window.location.search);
const id = params.get("IDNavi");

console.log(id) // "194"

or... if you have a URI address already as String

const uriString = "https://example.de/App_AspxFiles/P_Bogendaten.aspx?IDNavi=194";
const id = new URL(uriString).searchParams.get("IDNavi");

console.log(id); // "194"

now that you extracted the desired ID, all it takes is to target the desired Element like i.e:

const EL_id = document.querySelector(`[id$="IDNavi=${id}"]`);

where the Attribute Selector [] is querying the DOM for an Element which id ends $= in IDNavi=194

Then, to get its parent use the Element's .closest() method:

const EL_id_parent = EL_id.closest(".nav_ebene_2");

and finally you can add the desired active class

EL_id_parent.classList.add("activemenu");

Demo time:
Make class active an element with ID ending in a specific query param value:

const uriString = "https://example.de/App_AspxFiles/P_Bogendaten.aspx?IDNavi=194";
const id = new URL(uriString).searchParams.get("IDNavi");

/*
// you should use this instead, the above is for this DEMO only 
const params = new URLSearchParams(window.location.search);
const id = params.get("IDNavi");
*/

const EL_id = document.querySelector(`[id$="IDNavi=${id}"]`);
const EL_id_parent = EL_id.closest(".nav_ebene_2");
EL_id_parent.classList.add("activemenu");
.activemenu {
  background: gold;
}
<nav id="PageNavigation">
  <div class="nav_ebene_2">
    <div role="button" class="nav-item" id="P_Bogendaten.aspx?IDNavi=194">
      <p>IDNavi=194</p>
    </div>
  </div>
  <div class="nav_ebene_2">
    <div role="button" class="nav-item" id="P_Bogendaten.aspx?IDNavi=195">
      <p>IDNavi=195</p>
    </div>
  </div>
</nav>

Upvotes: 1

Related Questions