Reputation: 47
I have some JS that currently gets the URL of a website, splits the URL to a particular string and stores it in a variable
I then have an IF statement that depending on that string will add a class to my links. However, the i can't get the IF statement to work. It seems to do the action even if the condition has been met.
Any help would be greatly appreciated!
https://codepen.io/Carrot654321/pen/YazXBv - Code here
const navLinks = document.querySelectorAll("nav ul li a")
var url = window.location.href;
url = url.split("/");
if (url[2] = "s.codepen.io") {
navLinks[1].classList.add("active");
}
else {
navLinks[3].classList.add("active");
}
Upvotes: 0
Views: 149
Reputation: 680
const navLinks = document.querySelectorAll("nav ul li a")
var url = window.location.href;
url = url.split("/");
if (url[2] === "s.codepen.io") {
navLinks[1].classList.add("active");
}
else {
navLinks[3].classList.add("active");
}
use ===
instead of =
and don't use ==
as you will experience weird behavior because ==
does type conversion before comparison.
have a look at this - https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons
Upvotes: 4
Reputation: 132
I suspect this is because you have a single equals instead of a triple equals.
if (url[2] = "s.codepen.io")
This is assigning a value instead of comparing on it so it always returns true.
It should be:
if (url[2] === "s.codepen.io")
Upvotes: 1