John Zetterman
John Zetterman

Reputation: 3

`if` condition only working for first div encountered

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?

Upvotes: 0

Views: 167

Answers (5)

Ian
Ian

Reputation: 50905

No need to check for anything, let the selector do it all.

$('navitem[rel=' + pathname + ']').toggleClass('navitem selected_menu');

Don't even include the if statement.

Upvotes: 1

HMartch
HMartch

Reputation: 728

Try using the .each method of JQuery to test all of your matching elements. Like this:

$('document').ready(function() {
    var pathname = window.location.pathname;
    pathname = pathname.replace('/MVC/', '');

    $('.navitem').each(function() {
        if ($(this).attr('rel') == pathname) {
            $(this).toggleClass('selected_menu');
        }
    });

});

Upvotes: 0

pimvdb
pimvdb

Reputation: 154818

You can't just use one comparison operation because you have to check all of the divs.

$(".navitem").filter(function() {
  return $(this).attr("rel") === pathname;  // filter out the correct one(s)
}).toggleClass("navitem selected_menu");

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.

Upvotes: 2

Mathew Thompson
Mathew Thompson

Reputation: 56429

You'll need to use a loop. Try this:

$(".navItem").each(function () {
    if (pathname == $(this).attr('rel')) {
        $(this).toggleClass('navitem selected_menu')
    }
});

Upvotes: 1

Fluidbyte
Fluidbyte

Reputation: 5210

You'll need to loop through them using each:

$('.navitem').each(function(){
    if (pathname == $(this).attr('rel')) {
        $(this).toggleClass('navitem selected_menu')
    }
});

Upvotes: 1

Related Questions