$(document).on('click', '.tree label', function(e) {
$(this).next('ul').fadeToggle();
e.stopPropagation();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="tree">
<li class="has">
<label class="container">ROOT<span class="total">(12) </span>
<input type="checkbox" name="domain[]" value="ROOT">
<span class="checkmark"></span></label></ul>
<ul style="display: none;">
<li><label class="container">CHILD<input type="checkbox" name="subject[]" value="CHILD"><span class="checkmark"></span></label></li>
</ul></li>
</ul>
When I click the first label it should fadeToggle
the next ul
. But as soon as it fades in it fades out automatically.
Can anyone please let me know where is the issue? Is HTML format is incorrect?
2
Answers
Your html markup is wrong. You haven’t closed the first
ul
.It does not fade out for me. Here’s a screenshot
Your last edit added a
</li></ul>
but they are misplaced – the</ul>
is not required at all, and the<li>
should be after the first checkbox. I’ve removed them in the code below.The code snippet does not display the problem you describe – the
CHILD
is not displayed at all. That’s because.next()
selects the next sibling. Sibling means an element at the same level in the DOM tree, but you’re looking for siblings of your<label>
. If you format the HTML correctly it is easier to see:If you have a series of these on the page, and the logic is that you really want the next one down, you could use
.closest()
to find the parentul
of the event click, and then use.next()
to get the followingul
. Like so: