Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
Can't remove body class previosly added with click event

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!