How to use in jQuery :not and hasClass() to get a specific element without a class

Alon picture Alon · Jan 5, 2012 · Viewed 195.6k times · Source

I have this line of code:

$('#sitesAccordion .groupOfSites').click(function() {
    var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
    console.log(lastOpenSite);
});

I get "false" instead of getting one of the other elements (assuming that there is one - and there must be). I guess the problem is with:

.hasClass(':not(.closedTab)');

What is the problem?

My purpose is to create my own accordion (without using jQuery UI)

and I am trying to write it like this:

$('#sitesAccordion .groupOfSites').click(function() {

    //Get the last opened tab
    var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');

    //Close last opened tab and add class
    lastOpenSite.hide().toggleClass('closedTab');

    //Open the current Tab
    $(this).children('.accordionContent').toggle('fast');

    // remove class from open tab
    $(this).toggleClass('closedTab');


});

Is this the best way? thanks, Alon

Answer

Dennis picture Dennis · Jan 5, 2012

Use the not function instead:

var lastOpenSite = $(this).siblings().not('.closedTab');

hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.