RRowan RRowan - 2 months ago 8
HTML Question

jQuery target next() html item

hi I have a list of items which is generated like so:

<li class="panel-title">Item 1<i class="fa pull-right fa-plus"></i></li>
<ul class="panel-body">...</ul>
<li class="panel-title">Item 2<i class="fa pull-right fa-plus"></i></li>
<ul class="panel-body">...</ul>
<li class="panel-title">Item 3<i class="fa pull-right fa-plus"></i></li>
<ul class="panel-body">...</ul>


Upon clicking an 'li' item I need only the next 'ul' to expand. Unsure how to solve this & whether next() is the right action
Heres my code

$('li.panel-title > .fa').on("click",function() {
var $currIcon = $(this);
var $contents = $('ul.panel-body');
if($currIcon.hasClass('fa-plus')) {

$currIcon.$contents.next().slideDown();
$currIcon.removeClass('fa-plus');
$currIcon.addClass('fa-minus');
} else if($currIcon.hasClass('fa-minus')) {
$currIcon.$contents.next().slideUp();
$currIcon.removeClass('fa-minus');
$currIcon.addClass('fa-plus');
}
});

Answer

Try this

$('li.panel-title > .fa').on("click",function() {
  var $currIcon = $(this); 
  var $contents = $('ul.panel-body');         
  if($currIcon.hasClass('fa-plus')) {
          $currIcon.parent().next().slideDown();             
          $currIcon.removeClass('fa-plus');
          $currIcon.addClass('fa-minus');             
  } else if($currIcon.hasClass('fa-minus')) {             
          $currIcon.parent().next().slideUp();                   
          $currIcon.removeClass('fa-minus');
          $currIcon.addClass('fa-plus');
  }  
 });
Comments