Derek Foulk
Derek Foulk

Reputation: 1902

How do you exclude an element from a jQuery function that is included in the selector?

I am making a dropdown menu and am trying to make the list items image change from a plus (when not opened) to a minus (when opened).

The first Tier (parent list items) are set to list-style:none; so when the .click() below executes, I want the .addClass('close'); to apply to everything EXCEPT the parent <li>'s...

The issue is, the selector used in the encompassing .click() function includes the parent list items.

What I need to do is say:

"Apply the class 'close' to $(this) EXCEPT the first (parent) <li>'s'"

Here is the jQuery:

$(document).ready(function(){

  $("#nav li").click(function(event){

    // My attempt (not working)...
    $(this).not("#nav > ul > li").addClass('close');

    event.stopPropagation();
    $(this).children("ul").slideToggle(100);

    $(".last, a").click(function(event){
      event.stopPropagation();
    });

  });

});

And the jsFiddle:

Click to View

So my attempt was the following:

$(this).not("#nav > ul > li").addClass('close');

That didn't work... So if anyone has any advice, it would be greatly appreciated! thanks :)

Update:

The class 'close' needed !important added to it. The jQuery was doing what it should. I will post an answer when I successfully remove the class upon closing the menu item.

Update (2):

Removed !important and changed class specification to #nav li.close. Thanks Adeneo!

Update (3):

Changed .addClass() to .toggleClass(). Seems to make this menu do what I wanted it to :) Thanks Sushanth -- for this suggestion!

Upvotes: 0

Views: 82

Answers (2)

Sushanth --
Sushanth --

Reputation: 55740

Use .toggleClass()

$(this).not("#nav > ul > li").toggleClass('close');

Assuming you are not adding/removing your class anywhere else in your code

Upvotes: 2

adeneo
adeneo

Reputation: 318182

Your problem is not being specific enough with the css selector.

using #nav li is more specific than just .close, to fix the problem use #nav li.close (not !important) :

#nav li.close {
    list-style-image:url(http://www.horsepowerfreaks.com/images/close.gif);
}

FIDDLE

Here's a little more on CSS specificity and inheritance

Upvotes: 3

Related Questions