-1

I'm trying to make a win condition, that if these three specific classes have been added to my h1 "tester", it alerts something. For some reason, the function is not working. It doesn't actually check if it contains any of the classes, and alerts the message either way.

Does anybody know why it's doing this, or what i'm doing wrong? Here's my code:

var diagonalRightX = ["CX", "EX", "GX"];

 function winTester() {

   if (document.getElementById("tester").classList.contains=("CX")) {
     alert(diagonalRightX);
   }
 }
<h1 id="tester" onclick="winTester()" class="CX, EX, GX">Click Me!</h1>
  • change `document.getElementById("tester").classList.contains=("CX")` to `document.getElementById("tester").classList.contains("CX")`. All you have to do is remove the equals sign :) – quicVO Feb 22 '21 at 20:36
  • 1
    `contains=("CX")` because contains is a method.... you are setting contains equal to a string. Look at MDN https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/contains. Remove the `=` – epascarello Feb 22 '21 at 20:37
  • The `class` attribute also doesn’t delimit its values with commas, but _only_ with spaces, so remove the commas. Inline event handlers like `onclick` are [not recommended](https://stackoverflow.com/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](https://stackoverflow.com/a/43459991/4642212) way of registering events. Always [use `addEventListener`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Feb 22 '21 at 20:40
  • Oooh! Works now! Is it possible to check for several classes? Ultimately, i'd like to check if the element contains the variable diagonalRightX / classes "CX", "EX", "GX". – Raivo Kleijsen Feb 22 '21 at 20:42
  • 1
    @RaivoKleijsen See [`some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) or [`every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every), e.g. [If classlist contains more than one specific class](https://stackoverflow.com/a/54190870/4642212). – Sebastian Simon Feb 22 '21 at 20:43
  • Dupe of https://stackoverflow.com/questions/54190763/if-classlist-contains-more-than-one-specific-class – epascarello Feb 22 '21 at 20:45
  • Aha right. so i've tried out the array.every, and I think i'm getting very close. This is what i've got, though it's displaying an error. var el = document.getElementById("tester"); function winTester() { if (diagonalRightX.every(diagonalRightX => el.classList.contains("CX", "EX", "GX"))) { alert("hello"); } } – Raivo Kleijsen Feb 22 '21 at 23:26

1 Answers1

1

Remove the assignment operator (=) after contains

  if (document.getElementById("tester").classList.contains("CX")) {
      alert(diagonalRightX);
  }
Ran Turner
  • 14,906
  • 5
  • 47
  • 53