middleendian middleendian - 1 year ago 58
HTML Question

Toggle state of multiple elements by clicking one of them

I have following structure on a page:

<div class="mycontainer">
<div class="mysubclass">
<div class="myheader">header 1</div>
<div class="mycontent">content 1</div>
<div class="mysubclass">
<div class="myheader">header 2</div>
<div class="mycontent">content 2</div>
<div class="mysubclass">
<div class="myheader">header 3</div>
<div class="mycontent">content 3</div>

I need to get the following behaviour:
Right after page load all of them are closed. When I click on the first mysubclass, its myheader and mycontent should get additional class active. When I click on it again it should be removed. All the other elements shouldn't become an active class.
When I klick on first mysubclass, its myheader and mycontent should get additional class active again. When I click a second mysubclass, the active classes should be removed from the first mysubclass and added to the elements of the second (clicked) mysubclass.

In fact I need to simulate opening and closing elements with content, so when it's closed, content is not visible, and when I cklick on an element it gets class active and content is shown.

My JQuery code is following:

$(".mysubclass").click(function(e) {

if ($(".myheader").hasClass("activ") && $(".mycontent").hasClass("activ")) {
} else {

How can I get this behaviour working without changing html code?
Here is my example of this problem: JSFiddle example .

Answer Source

This should work

 $(".mysubclass").click(function(e) { 
   if ($(this).find(".myheader").hasClass("active") && $(this).find(".mycontent").hasClass("active")) {

} else {
    $(".mycontainer .active").removeClass("active");


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download