Reputation: 5532
Toggle is not working with sub class (.open
), it works with main tag (li
).
$('.open').click(function() {
$(this).next('ul').toggle();
});
Anything am I missing?
Upvotes: 1
Views: 126
Reputation: 99
When you put $(this).next('ul').toggle();
it targets to the next ul inside the <li>
where the .open object is located, but there is no <ul>
there.
For that, you should use target the parent <li>
and then target the next <ul>
that follows it.
The code should be something like this:
$('.open').click(function() {
$(this).parent().next('ul').toggle();
});
Upvotes: 0
Reputation: 1932
Get the parent li
element for the .open
and then get the next li
element for that partent item.
$('.open').click(function() {
$(this).parent('li').next('ul').toggle();
});
Upvotes: 0
Reputation: 67505
The jQuery method next()
get the immediately following sibling.
Problem : You .open
element doesn't have an ul
sibling.
Suggested solution : Go up to the parent li
then use the .next()
that will target the ul
sibling like :
$(this).parent().next('ul').toggle();
//Or
$(this).parents('li').next('ul').toggle();
Hope this helps.
$('.open').click(function() {
$(this).parent().next('ul').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li> 11111111 <i class="open">open</i></li>
<ul>
<li> 1.1 </li>
<li> 1.2 </li>
</ul>
<li> 22222222222 <i class="open">open</i></li>
<ul>
<li> 2.1 </li>
<li> 2.2 </li>
</ul>
</ul>
Upvotes: 1
Reputation: 15393
Use .closest()
for get the neareast closest element li .next()
for select immediate ul element in the dom
$('.open').click(function() {
$(this).closest('li').next('ul').toggle();
});
Upvotes: 0