Problem removing/adding class in Javascript

Asked

Viewed 92 times

1

I am trying to get a button to remove or add a class in the body, but this giving the following error when clicking the "Uncaught Typeerror: Cannot read Property 'classList' of null"

var body = document.querySelector('div.single-news');
var button = document.querySelector('button#skin-btn');
button.addEventListener('click', function() {
    body.classList.toggle('light-skin');
});

The ideal would be to make the code with pure JS.

Updated with the HTML:

var menu = document.querySelector('div.single-news');
var button = document.querySelector('button#skin-btn');
botao.addEventListener('click', function() {
  var open = menu.classList.contains('light-skin');
  menu.classList.toggle('light-skin');
});
<body class="entry-header single-news">
  <button class="night-mode-btn" id="skin-btn">
    <span class="night-mode-btn__text">Modo noturno</span>
  </button>
  <h1 class="entry-title">
    {{ post.title }}
  </h1>
  <time class="entry-postedon">
    <span class="screen-reader-text">Publicado em</span> 
    {{ post.post_date|date("j \\d\\e F \\d\\e Y") }} às {{ post.time|date("H\\hi") }}
  </time>
  {% if post.thumbnail %}
  <div class="entry-cover-image">
    <img data-dynsrc="['{{ post.thumbnail.src('img-16x9-760x428') }}']" data-fullscreen-url="{{ post.thumbnail.src('large') }}">
  </div>
  {% endif %}
</body>

  • Post also your html :)

  • You’ll be putting that script on head before the browser has read HTML? Place the script at the bottom of the page, before </body>.

  • That’s it. I’m putting the <script> at the end of the code, before the </body>. I updated it as html

  • You are using var menu = Document.querySelector('div.single-news') and there is no div with this class in your html. There is this class in body....

  • André, your problem is very simple, you don’t have a div.single-news and yes body.single-news, then the selector div.single-news returns nothing,

  • That’s all it was! : Thank you, Leon and Tobias!

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.