Makk Makk - 2 months ago 8
jQuery Question

jquery selecting parent from this and then its child

I need to select a parent of 'this' element then it's child can you see if my code is correct?

$(this).click(function(){
$(this).parent('li').child('p').toggle();
$(this).not(this).parent('li').child('p').toggle('hide');
});


This is actually for a html which looks somewhat like this

<ul>
<li><header>Header 1</header><p>Content 1</p></li>
<li><header>Header 2</header><p>Content 2</p></li>
</ul>


Can you explain me whether if the script is correct?

Answer

var $contents = $("ul p"); // get 'em all! (and use class to be more specific)

$('header').click(function(){
  var $myContent = $(this).closest('li').find('p'); // this content
  $contents.not($myContent).hide();                 // hide all other
  $myContent.toggle();                              // this content toggle
});
ul p{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><header>Header 1</header><p>Content 1</p></li>
  <li><header>Header 2</header><p>Content 2</p></li>
  <li><header>Header 3</header><p>Content 3</p></li>
</ul>

Comments