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.
HTML:
<div class="mainmenu "onclick="hideshowmenu()">RED1</div>
<div id="submenu" class="submenu">
<div class="mainmenu "onclick="hideshowmenu()">RED2</div>
<div id="box" class="box">
js:
function hideshowmenu() {
var element = document.getElementsByClassName("box");
element.classList.toggle("bg-red");
}
CSS:
.bg-red{
margin-top:10px;
background-color:red;
height:20px;
}
CodePudding user response:
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");
}
CodePudding user response:
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/
CodePudding user response:
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");
}
CodePudding user response:
here is an example
function hideshowmenu() {
var element = document.getElementById("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>
<div class="mainmenu "onclick="hideshowmenu()">RED2</div>
<div id="box" class="box">fdeefd</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>