-1

I've been trying to use classList as described in the documentation here:

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

However, I keep getting errors in the browser saying 'contains' or 'add' is undefined. I don't understand why.

I've used:

for (i = 0; i < card.length; i++) {
        card[i].addEventListener('click', function () {
            this.classList.toggle('open');
            this.classList.toggle('show');
        });  

And classList works great!!. However, when I write:

 let flipped = document.classList.contains('open');

I get the error "contains" is undefined.

If anybody can explain to me how these uses of classList are different I would be incredibly thankful!!

Side Note: I'm using pure javascript and troubleshooting in chrome

Bharata
  • 13,509
  • 6
  • 36
  • 50
ab3d_work
  • 185
  • 3
  • 16
  • 2
    The title of the linked MDN article is "_Element.classList_". The said object is a property of elements only, `document` doesn't have it. Notice, that the error message is "_Cannot read property 'contains' of undefined_", that means `document.classList` being `undefined`. In FireFox the error messge is more clear: "_document.classList is undefined_". – Teemu Jul 12 '18 at 14:39
  • `document.body.classList` is work. – flowerszhong Jul 12 '18 at 14:54
  • @flowerszhong, because **[`body`](https://developer.mozilla.org/ru/docs/Web/API/Document/body)** is an element. See my answer. – Bharata Jul 12 '18 at 14:57
  • A `document` has no attributes, and no `class` either. Did you mean `document.documentElement` maybe`? – Bergi Jul 12 '18 at 15:53

1 Answers1

1

You have this error because classList is the object in Element and not in document.

Fox example:

var flipped = document.classList; //undefined
console.log(flipped); //undefined

And then if you try to use flipped.contains you get an error because flipped is undefined.

Bharata
  • 13,509
  • 6
  • 36
  • 50