Hello,
So I have a ul-list with tree structure and what I would like it to do is open and close branches from the “Toggle” text. Here is the code:
<script src="jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$('.toggle').on('click', function(){
// There must be a better way than this to obtain the children ul's?
var tmp = $(this);
tmp.parent().parent().children().find('ul').slideToggle("slow");
var isOpen = $(this).hasClass('opened');
if(isOpen){
$(this).removeClass('opened').addClass('closed');
$(this).text('Open');
} else {
$(this).text('Close');
$(this).removeClass('closed').addClass('opened');
}
});
});
</script>
<ul>
<li>
<h1>1</h1><span class="toggle opened">Toggle</span>
<ul>
<li><h2>1.1</h2></li>
<li><h2>1.2</h2></li>
</ul>
</li>
<li>
<h1>2</h1><span class="toggle opened">Toggle</span>
<ul>
<li><h2>2.1</h2></li>
<li>
<h2>2.2</h2><span class="toggle opened">Toggle</span>
<ul>
<li><h3>2.2.1</h3></li>
<li><h3>2.2.2</h3></li>
</ul>
</li>
</ul>
</li>
</ul>
This works fine on the children branches but when I try to close 1 or 2 e.g on line <h1>1</h1><span class="toggle opened">Toggle</span>
it closes the whole tree instead of just closing children of 1. I think I know the reason why this happens, my current code will search the root ul when main headings toggle is clicked and that is why it closes everything. But I don’t know how to solve this so it would work as expected. Any help?