简体   繁体   中英

Show and hide parent and children divs using jQuery

I have a div which contains children html elements, when I click on div children elements will display, in that hide button also there when I click on hide parent will hide. please help me

Use display: none in css on the div you want to hide. If you want to show them, use $("#yourdiv").css("display","block"); in your jquery.

It is better if you can post your relevant code, anyway here example made for you :

HTML

<div class="parent">Hey All
  <div>a</div>
  <div>b</div>
  <div>c
    <button class="hide" data-type="parent">Hide Parent</button>
    <button class="hide" data-type="children">Hide Children</button>
  </div>
</div>
<div class="parent">Hey All 1
 <div>a</div>
 <div>b</div>
 <div>c
    <button class="hide" data-type="parent">Hide Parent</button>
    <button class="hide" data-type="children">Hide Children</button>
</div>

JS

$('.parent').click(function () {
  // show direct child when parent div was clicked
  $(this).children().css('display', 'block');
});

// hide parent or child
$('.hide').click(function (e) {
  e.stopPropagation();
  var type = $(this).data('type');
  var parent = $(this).closest('.parent');

  if (type === "parent") parent.css('display', 'none');
  else parent.children().css('display', 'none');
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM