I’m trying to swap out one class for another when a page loads depending on the directory in the URL. My code is working for the first div in my menu, but not for any others. Here’s the code:
$('document').ready(function() {
var pathname = window.location.pathname;
pathname = pathname.replace('/MVC/', '');
if (pathname == $('.navitem').attr('rel')) {
$('.navitem[rel='+pathname+']').toggleClass('navitem selected_menu')
}
});
The HTML is as follows:
<div class="navitem" rel="dashboard"><a href="http://localhost/MVC/dashboard">Dashboard</a></div>
<div class="navitem" rel="chat"><a href="http://localhost/MVC/chat">Chat</a></div>
<div class="navitem" rel="users"><a href="http://localhost/MVC/user">Users</a</div>
When I alert($('.navitem').attr('rel')), it always returns the rel value of the first div. How do I get it to look at all of them instead of just the first one?
You can’t just use one comparison operation because you have to check all of the
divs.By the way, it is usually
$(document).ready. Although it doesn’t matter what you pass to$in case of.ready, this is the de facto standard.