Elyor
Elyor

Reputation: 5532

Toggle list using sub class

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?

jsfiddle

Upvotes: 1

Views: 126

Answers (4)

Sergio de Propios
Sergio de Propios

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

Aamir
Aamir

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

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Updated fiddle

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

Sudharsan S
Sudharsan S

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();
});

Fiddle

Upvotes: 0

Related Questions