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 :)
– MarceloBoni
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>
.– Sergio
That’s it. I’m putting the <script> at the end of the code, before the </body>. I updated it as html
– André Bisewski
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....
– LLeon
André, your problem is very simple, you don’t have a
div.single-news
and yesbody.single-news
, then the selectordiv.single-news
returns nothing,– Tobias Mesquita
That’s all it was! : Thank you, Leon and Tobias!
– André Bisewski