Reputation: 13
i am making a navigation bar and want the class `active to be added when i am on that specific page
code bellow is not ruining with the if statement (shown with comment)
<html>
<head>
<style>
.active {
color: red;
}
</style>
</head>
<body>
<a href="a.html" class="nav-item">nav</a>
<a href="b.html" class="nav-item">nav</a>
<p id="z">aaa</p>
<p id="zz"></p>
<script>
var navClass = document.getElementsByClassName("nav-item");
var path = window.location.href;
for (i = 0; i < navClass.length; i++) {
//my issue
if (navClass[i] === path) {
navClass[i].classList.add("active");
}
}
//for testing
var xx = navClass[0];//.getAttribute("herf");
document.getElementById("zz").innerHTML = xx + "<br>" + path;
</script>
</body>
</html>
Upvotes: 0
Views: 422
Reputation: 96
The variables you are working with are formatted slightly differently than your code implies you are expecting them to be.
If you open up your console and access the window.location.href variable you'll see it contains a full valid URL, rather than relative format the links in your navigation follow, so your absolute test (===) will fail every time, as they will never be equal.
https://stackoverflow.com/questions/54508836/if-statement-not-working-with-classlist-add
does not equal
if-statement-not-working-with-classlist-add
You could solve the problem by making the navigation links absolute, but that will cause more problems for you down the road.
If you change your test from comparing the two to looking for the navigation's href inside the path variable your code will work. Additionally, you'll need to test against the href attribute of your object, not the object itself.
Change:
if (navClass[i] === path) {
To:
if (path.includes(navClass[i].href)) {
Edited: Forgot to add .href attribute to suggested change
Upvotes: 1
Reputation: 44135
You need to change how you're detecting, and how you're adding. Also make navClass
an array, not a NodeList:
var navClass = Array.prototype.slice.call(document.getElementsByClassName("nav-item"));
var path = window.location.href;
navClass.forEach(elem => {
if (path.includes(elem.href)) {
elem.classList.add("active");
}
});
Upvotes: 0