mamta mamta - 5 months ago 10
PHP Question

How to find a particular class using javascript?

Hii all I am creating a

accordion
with use of pure
javascript
. Initailly I have shown content of only first section. Then by using
javascript
I am showing content on clicking sections.This works well but when I click on section1 it does not hide because
active
class
is still there. Please help. Any help is apprecated

<!DOCTYPE html>
<html>
<head>
<style>
.main {
background-color: #eee;
width:350px;
color: #444;
padding: 18px;
border: none;
text-align: left;
font-size: 15px;

}

.main.active,.main:hover {
background-color: #ddd;
}

div.panel {
padding: 0 18px;
background-color: white;
display:none;
width:350px;


}
.active{
display: block !important;

}

div.panel.show {
display: block;
}
div.panel.hide {
display: none;
}
</style>
</head>
<body>
<div class="main">Section 1</div>
<div class="panel active">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<div class="main">Section 2</div>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<div class="main">Section 3</div>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<script>
var acc = document.getElementsByClassName("main");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.nextElementSibling.classList.toggle("show");
}
}
</script>

</body>
</html>

Answer

why don't you just give your first panel class show instead of active? active class seems redundant in your code.

code for the first panel:

<div class="panel show">
Comments