0

I'm having a hard time trying to understand why this is not working as expected.

I simply am trying to target the body element, but only if does not contain the .logged-in class, but with the code below I get a log to the console whether the class exists or not.

if ($('body:not(.logged-in)')) {
    console.log('Hi!');
}

...or...

if ($('body').not('.logged-in')) {
    console.log('Hi!');
}

Am I missing something here?

Brett
  • 19,449
  • 54
  • 157
  • 290

1 Answers1

1

Those selectors actually skip (remove from the whole selected elements) the elements with class logged-in.

I recommend you to use the attribute length in order to check the existence of an element.

if ($('body').find('.logged-in').length) { 
    console.log('Exists!');
}
Ele
  • 33,468
  • 7
  • 37
  • 75
  • Ahhh.... yeah I see what you mean, I knew I had to be doing something stupid. So it basically is selecting the element (doing it's job) and hence is always returning true. – Brett Apr 21 '19 at 22:16
  • @Brett this `$('body:not(.logged-in)')` is returning something, and for js engine is a truthy (`true`) value. So, always the condition is `true`. – Ele Apr 21 '19 at 22:18