-3

How can I add a class to the body in ES6 JS?

I've tried:

let body = document.getElementsByTagName('body');
body.classList.add('my-class');

It fails. No Jquery please.

panthro
  • 22,779
  • 66
  • 183
  • 324
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Sebastian Simon Mar 20 '17 at 15:34
  • 7
    Use `document.body` instead of `document.getElementsByTagName('body')`. `getElementsByTagName` returns an `HTMLCollection`. They don’t have `classList`s. The console should’ve told you already. – Sebastian Simon Mar 20 '17 at 15:34
  • 1
    fix: `body[0].classList` – Alex Mar 20 '17 at 15:44
  • also a minor thing, if you don't intend to change the variable value, consider using `const` instead of `let` – pwolaq Mar 20 '17 at 15:58

1 Answers1

1

I think the problem for your code is document.getElementsByTagName('body') will return a HTMLCollection, you need to

let body = document.getElementsByTagName('body')[0];

there is an example https://plnkr.co/edit/MFTB95gzYZOYKIJvc5DK?p=preview

YoungLearnsToCoding
  • 427
  • 1
  • 3
  • 10