My goal is to display a list everytime the button is pressed kind of like a dropdown list, so I made a sort of test html,css and js files and somehow it doesn't work, the log function in my js code outputs the word 'year' on the console but the class list toggle doesn't seem to change/add the "active" on the divs' class.
Below is my js.
function btnFunction(identifier){
console.log(identifier)
var element = document.getElementById(identifier);
element.classList.toggle("active");}
Below is my html.
<div class="modal-content-col-6-drop">
<button onclick="btnFunction('year')" class="drop-btn">sample</button>
</div>
<div id="year" class="select">
<ul>
<li>0 Year</li>
<li>1 Year</li>
</ul>
</div>
Below is my css.
#year{
display: none;
}
.active{
display: block;
}
The css selctor based on id is prioritized over one based on class. So the id year will always be display: none even if it has the class active. The best solution is to not use ids for css selectors because of this.
A better solution would be
.select{
display: none;
}
.select.active{
display: block;
}
You can read more about selector specificity here.
Ill include a snippet that shows this under here:
function btnFunction(identifier){
console.log(identifier)
var element = document.getElementById(identifier);
element.classList.toggle("active");
}
.select{
display: none;
}
.select.active{
display: block;
}
<html>
<body>
<div class="modal-content-col-6-drop">
<button onclick="btnFunction('year')" class="drop-btn">sample</button>
</div>
<div id="year" class="select">
<ul>
<li>0 Year</li>
<li>1 Year</li>
</ul>
</div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With