Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 677
Alon Avatar asked Jan 05 '12 13:01

Alon


People also ask

How do I target a specific element in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do you check if an element doesn't have a class?

The contains() method returns true if the element has the provided class and false otherwise.

How do you check whether a class is used in jQuery or not?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


2 Answers

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.

like image 134
Dennis Avatar answered Oct 02 '22 11:10

Dennis


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.

like image 39
Qar Avatar answered Oct 02 '22 11:10

Qar