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

315
Views
CSS: Error in Toggle Classes By using Class name

i am trying to toggle classes by using class name. My code is working fine when i am toggling using id. how can i make it work only one red should be visible at one time.

function hideshowmenu() {
  var element = document.getElementsByClassName("box");
  element.classList.toggle("bg-red");
}
.bg-red {
  margin-top: 10px;
  background-color: red;
  height: 20px;
}
<div class="mainmenu " onclick="hideshowmenu()">RED1</div>
<div id="submenu" class="submenu">
  <div class="mainmenu " onclick="hideshowmenu()">RED2</div>
  <div id="box" class="box"> </div>
</div>

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

0

As the name of getElementsByClassName suggest, it returns elementS, so you are getting HTMLCollection, not one element. Query the first one, like this:

function hideshowmenu() {
  var element = document.getElementsByClassName("box")[0];
  element.classList.toggle("bg-red");
}

or:

function hideshowmenu() {
  var elements = document.getElementsByClassName("box");
  elements[0].classList.toggle("bg-red");
}
about 4 years ago · Juan Pablo Isaza Report

0

What is returned by document.getElementsByClassName("box"); is a collection. You need to specify the index to access the classList property.

You are doing:

var element = document.getElementsByClassName("box");
element.classList.toggle("bg-red");

When you should be doing

var element = document.getElementsByClassName("box");
element[0].classList.toggle("bg-red");

You could also loop through the elements if you want to toggle multiple values.

Example code fiddle https://jsfiddle.net/agy5jtb0/1/

about 4 years ago · Juan Pablo Isaza Report

0

getElementsByClassName("box") return a collection of elements, but you considered it as a single element that is your mistake. I suggest something like this:

html:

<div class="mainmenu " onclick="hideshowmenu(this)">RED1</div>
<div id="submenu" class="submenu">
    <div class="mainmenu" onclick="hideshowmenu(this)">RED2</div>
    <div id="box" class="box"></div>
</div>

js:

function hideshowmenu(el) {
    el.classList.toggle("bg-red");
}
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!