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

225
Views
How to add class via Javascript instead of work with css inside js code?

I'm building a sidenav menu. I want to work on the style directly in the css file instead of the Javascript code as below.

For example: dropContent.style.display === "block" and "none", I wish there was a class to modify and not add css values inside the js code. Is this possible ?

References: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sidenav_dropdown

var dropdown = document.getElementsByClassName("dropdown-btn");
var i;

  for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
  this.classList.toggle("activate");
  
  var dropContent = this.nextElementSibling;
  if (dropContent.style.display === "block") {
      dropContent.style.display = "none";
    } else {
      dropContent.style.display = "block";
    }
  });
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In your CSS:

.hidden {
  display: none;
}

In your JS:

if (element.classList.contains("hidden")) {
  element.classList.remove("hidden");
} else {
  element.classList.add("hidden");
}

Make sure your element has the display property block to start with and I believe this should give you what you want.

Edit: As @tacoshy points out, there's the toggle function, which is much clearer:

element.classList.toggle("hidden");
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!