-1

Hello friends I have this code that works well for me to check if my element contains a certain class, but I want to achieve the opposite, that it checks me when this class does not contain the element.

if (document.querySelector(".header").classList.contains("no-sticky")) {
      alert();
    }
mike jet
  • 21
  • 1
  • 1
  • 1
  • 3
    Why not use the *not* symbol `!` – zero298 Feb 22 '21 at 13:22
  • Write it like: `if (!document.querySelector(".header").classList.contains("no-sticky")) { alert(); }` –  Feb 22 '21 at 13:23
  • just to be pedantic and for brevity, there is the `else` also ‍♂️ – Pogrindis Feb 22 '21 at 13:24
  • 1
    Does this answer your question? [How to check if an element does NOT have a specific class?](https://stackoverflow.com/questions/7841048/how-to-check-if-an-element-does-not-have-a-specific-class) –  Feb 22 '21 at 13:24
  • Hi Friends, exactly where should I use the "!" I tried putting it before "! .classList.contains" and it didn't work :( – mike jet Feb 22 '21 at 13:25
  • 1
    I’m surprised you were not able to find the solution in whatever search you did prior. – Paul Samsotha Feb 22 '21 at 13:25
  • This link: [enter link description here](https://stackoverflow.com/questions/5898656/check-if-an-element-contains-a-class-in-javascript) – Elikar Kanane Mugangane Feb 22 '21 at 13:26
  • @poPaTheGuru Thanks friend that worked for me. I am very grateful to you – mike jet Feb 22 '21 at 13:35

1 Answers1

4

Just put exclamation mark in front of the condition.

if (!document.querySelector(".header").classList.contains("no-sticky")) {
      alert();
    }```
İlker
  • 1,872
  • 1
  • 12
  • 28
  • Thanks friend this worked for me, I know it is something very simple but I do not know much pure javascript, I thank you very much this was driving me crazy – mike jet Feb 22 '21 at 13:29
  • Thanks! It's working for me now with `if (!x.classList.contains("my-class"))` but I'm curious as to why `if x.classList.contains("my-class")!==true` didn't work, and also why `if x.classList.contains("my-class")===false` didn't work. If anyone is willing to explain why, comments are welcome and appreciated. – Mentalist Jul 28 '23 at 06:51