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

211,081

Solution 1

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.

Solution 2

It's much easier to do like this:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

Solution 3

jQuery's hasClass() method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.

For ex: x.hasClass('error');

Solution 4

You can also use jQuery - is(selector) Method:

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

Solution 5

I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.

 $(this).siblings(':not(.closedTab)');
Share:
211,081
Alon
Author by

Alon

Updated on July 05, 2022

Comments

  • Alon
    Alon almost 2 years

    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

  • Alon
    Alon over 12 years
    ohh - that was a silly mistake I did - thanks for the answer!
  • James Allardice
    James Allardice almost 12 years
    This won't work for what the OP is trying to do. It just tests whether #foo has a class or not, it doesn't reduce the matched set of elements to those that have it.
  • Rich Finelli
    Rich Finelli about 9 years
    this way works pretty good in my totally different situation. thanks.
  • Galzor
    Galzor over 5 years
    all i was doing wrong was putting ! with braces !($(this).hasClass()) that didnt worked.