So, do not rush to reproach me saying that similar questions are a dime a dozen. Now I work with lists, and the current task when clicking on an item in the list is to show another, adjacent - sub-element hidden by default. When you click again - to hide it. When clicking on neighboring elements, return the remaining elements to the default state and work only with the current element on which the click is made. I managed to implement everything, but separately and the problem is to glue the script together. From words to deeds:

$(".click-elem").on("click", function() { var clickId = $(this).attr("data-number"); // Участок №1 $("h4").removeClass("active"); $(clickId).addClass("active"); // Участок №2 // var numberFilter = /\d+/g; // var elemIndex = clickId.match(numberFilter); // var element = document.getElementById(elemIndex); // element.classList.toggle("active"); }); 
 .list ul li div h4 { visibility: hidden; } .click-elem { cursor: pointer; } .active { visibility: visible !important; color: lime; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="list"> <ul> <li> <div> <p data-number="#0" class="click-elem">First element</p> <h4 id="0">This is first subelement</h4> </div> </li> <li> <div> <p data-number='#1' class="click-elem">Second element</p> <h4 id="1">This is second subelement</h4> </div> </li> <li> <div> <p data-number='#2' class="click-elem">Third element</p> <h4 id="2">This is third subelement</h4> </div> </li> </ul> </div> 

Now the script works correctly only in part, alas. When you click a sub element, when you click on another element, the previous one hides and the current one is activated - everything is fine, but what if the user wants to hide the current sub element? Nothing will come of it. For this, I finished the existing script - this is plot number 2. But he is in conflict with the previous code and now stops plot number 1. Therefore, part of the code is commented. Half a day I break my head - to no avail. Help pzhlst) I apologize in advance for the impediment, I tried to describe the problem as clearly as possible. Link to pen: https://codepen.io/Metalspell/pen/WLpqZJ

    1 answer 1

    You probably mean it:

     $(".click-elem").on("click", function() { var clickId = $(this).attr("data-number"); // Участок №1 if (!$(clickId).hasClass("active")) { $("h4").removeClass("active"); $(clickId).addClass("active"); } else { $(clickId).removeClass("active"); } // Участок №2 // var numberFilter = /\d+/g; // var elemIndex = clickId.match(numberFilter); // var element = document.getElementById(elemIndex); // element.classList.toggle("active"); }); 

    Check here: https://codepen.io/anon/pen/wRdwmW

    • Exactly! Thank. Of course, looking now at the implementation, I think how I myself didn’t think of it because everything is simple. And yet ... - Dmitry Borgir