simple jQuery addClass() doesn't seem to be working
javascript, jquery
Solution
Assign `href` to `a`;
<nav id="links">
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
Then try:
var pathname = window.location.pathname;
$("#links ul li a").each( function() {
var href= $(this).attr("href");
if (href.length && pathname.indexOf(href) >= 0){
$(this).addClass("active");
}
});
If you can't change the HTML then try like following:
var pathname = window.location.pathname;
$("#links ul li a").each( function() {
var href= $(this).attr("href");
if (href != undefined && pathname.indexOf(href) >= 0){
$(this).addClass("active");
}
});
Problem
I want to be able to determine what page the user is currently on. a simple indicator in the form of adding unique style to the navigation link the user is currently viewing its context here is my script, all selectors working fine, if statement also do the job, but the addClass() function does nothing.. here is my code: ``` <script> $(document).ready(function(){ var pathname = window.location.pathname; $("#links ul li a").each( function() { var href= $(this).attr("href"); if (pathname.indexOf(href) >= 0){ $(this).addClass("active"); } } ); }); </script> <nav id="links"> <ul> <li><a href="index.php">Home</a></li> <li><a>About</a></li> <li><a>Contact</a></li> </ul> </nav> ``` HTML : got it to work ,this is my finaly code, is there a need for any improvments ? ``` $(document).ready(function(){ var pathname = window.location.pathname; var onDomain=true; $("#links ul li a").each( function() { var href= $(this).attr("href"); if (href != undefined && pathname.indexOf(href) >= 0){ $(this).addClass("active"); onDomain=false; } }); if (onDomain){ $("#links ul li:first-child a").addClass("active"); } }); ```