Rob
Rob

Reputation: 213

Show first element in a div and hide the rest

I've currently got this code working that hides everything bar the first 'p' tag, then fires a click function to toggle the rest of the divs' p elements:

<div class="col">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
<ul>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
   <li>Vestibulum auctor dapibus neque.</li>
</ul>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>           
<div class="sub-content-btn">Find out more</div>
</div>
jQuery('.col').each(function() { 
    jQuery(this).find('p:not(:first)').hide();
  });

  jQuery('.sub-content-btn').click(function() {
    jQuery(this).toggleClass('active');
    if(jQuery(this).hasClass('active')){
      jQuery(this).parent('.col').find('p').show();
    } else {
      jQuery(this).parent('.col').find('p').hide();
      jQuery(this).parent('.col').find('p:first').show();
    }
  });

How can i amend this code to hide p tags and ul elements not just the p tag, then toggle all elements? The div in question will has ul's in it.

Upvotes: 1

Views: 4280

Answers (2)

bipen
bipen

Reputation: 36531

try this

jQuery('.col').each(function() { 
  var $this= jQuery(this);
  $this.find(':not(p:first, .sub-content-btn)').hide();

});

jQuery('.sub-content-btn').click(function() {
  var $this= jQuery(this);
  var $parent=  $this.parent('.col');
  $this.toggleClass('active');
  if($this.hasClass('active')){
    $parent.find('p').show();
  } else {
    $parent.find('p').hide();
    $parent.find('ul').hide();
    $parent.find('p:first').show();
 }
});

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337590

Try this:

jQuery('.col').each(function () {
  jQuery(this).find(':not(p:first, .sub-content-btn)').hide();
});

jQuery('.sub-content-btn').click(function () {
  var $btn = jQuery(this);
  $btn.toggleClass('active');
  if ($btn.hasClass('active')) {
    $btn.siblings().show();
  } else {
    $btn.siblings().not('p:first').hide();
  }
});

Example fiddle

Upvotes: 0

Related Questions