0

I know already that the ! is used generally to express negation like no, not, and null in JavaScript.

But what does the exclamation mark mean before a selector in jQuery?

if(!$('selector').hasClass('something')){do something}
Keavon
  • 6,837
  • 9
  • 51
  • 79

3 Answers3

9

It negates a boolean.

Meaning:

true becomes false

and

false becomes true


In this example it means:

if(!$('selector').hasClass('something'))

if selector has not class something

The exclamation mark does not apply on the jQuery selector but on the result of the hasClass function. It is like you have used brackets (but you don't have to use brackets, JavaScript knows that this is meant).

!( $('selector').hasClass('something') /* e.g. returns true */ ) /* now it's false */
idmean
  • 14,540
  • 9
  • 54
  • 83
1

It simply means if NOT then do something so it works opposite to the usual if condition.

For example, the below are same :

if(true) { //or if(something == true)
   //Do something
}

if(!false) { //or if(something != false)
   //Do something
}

So in your case, if your selector returns false then do something.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
0

is also means the same negation meaning, but you can also use

if($('selector.something').length){do something}

because in jquery if it do not found elements its length is 0;

also in some situation you can use

$('select(:not(:attributor)')

for example

$('option(:not(:selected))')

is the same as

!$('option:selected')

might this can help you!

Will
  • 221
  • 3
  • 12