I'm missing something, probably related with bind, but I can not see what and where. I can add a class to a body tag, but I can not remove it latter.
const add_body_class = document.querySelectorAll('.btn-add-class');
add_body_class.forEach(item => {
item.addEventListener('click', event => {
document.body.classList.add('foobar');
})
});
const remove_body_class = document.querySelectorAll('.btn-remove-class');
remove_body_class.forEach(item => {
item.addEventListener('click', event => {
// this doesn't work
document.body.classList.remove('foobar');
// click event works
console.log("clicked");
})
});
BTW I need to use multiple selectors and document.querySelectorAll because of multiple instances, and I can not change any of HTML code.
Any help would be appreciated!
It works fine for me, I just wrapped it inside a DOMContentLoaded listener.
<!DOCTYPE html>
<html>
<body>
<button class="btn-add-class">Add</button>
<button class="btn-add-class">Add</button>
<button class="btn-add-class">Add</button>
<hr>
<button class="btn-remove-class">Remove</button>
<button class="btn-remove-class">Remove</button>
<button class="btn-remove-class">Remove</button>
</body>
<style>
.foobar{
background-color: yellow;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", () => {
const add_body_class = document.querySelectorAll('.btn-add-class');
add_body_class.forEach(item => {
item.addEventListener('click', event => {
document.body.classList.add('foobar');
console.log("added");
})
});
const remove_body_class = document.querySelectorAll('.btn-remove-class');
remove_body_class.forEach(item => {
item.addEventListener('click', event => {
// this doesn't work
document.body.classList.remove('foobar');
// click event works
console.log("removed");
})
});
})
</script>
</html>