-3

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
  • 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

2

Just put exclamation mark in front of the condition.

if (!document.querySelector(".header").classList.contains("no-sticky")) {
      alert();
    }```
İlker
  • 1,506
  • 1
  • 8
  • 19
  • 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