Expand Only the Child Div Within Parent

Question

I'm trying to only show a child div when the parent div's text is shown, instead of all the other divs with the same name. Imagine four div's with classes of "lead" and within those leads, there is a normaldiv child. Rather than open all the childs in other lead divs, I only want the one child within each lead.

Example HTML:

<div class="lead"><div class="normaldiv">1</div></div>
<div class="lead"><div class="normaldiv">2</div></div>
<div class="lead"><div class="normaldiv">3</div></div>
<div class="lead"><div class="normaldiv">4</div></div>

jQuery - this expands all normal divs

$(".lead").click(function() {
  $(".normaldiv").slideToggle("slow");
});

Tested:

$(this).parent().children(".normaldiv").slideToggle("slow");

The tested one I thought would grab all the children within the parent div and only expand those on a click. However, nothing shows up on a click event.


Show source
| jquery   | html   2017-01-03 18:01 3 Answers

Answers ( 3 )

  1. 2017-01-03 18:01

    Use $(this).find(".normaldiv") inside your click listener to select only the normaldiv inside the lead element - see demo below:

    $(".lead").click(function() {
      $(this).find(".normaldiv").slideToggle("slow");
    });
    <div class="lead"><div class="normaldiv">1</div></div>
    <div class="lead"><div class="normaldiv">2</div></div>
    <div class="lead"><div class="normaldiv">3</div></div>
    <div class="lead"><div class="normaldiv">4</div></div>

  2. 2017-01-03 18:01

    grab only the children not the parent children

    $(".lead").click(function() {
    //  $(".normaldiv").slideToggle("slow");
      $(this).children(".normaldiv").slideToggle("slow");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="lead"><div class="normaldiv">1</div></div>
    <div class="lead"><div class="normaldiv">2</div></div>
    <div class="lead"><div class="normaldiv">3</div></div>
    <div class="lead"><div class="normaldiv">4</div></div>

  3. 2017-01-03 18:01

    You need to select the children of the .lead elements that you are selecting.

    What you are doing currently in the second example is selecting the parent of the .lead element (some container element), and then trying to select .normaldiv out of its children (which are only .lead elements).

    $(".lead").click(function() {
      $(this).children(".normaldiv").slideToggle("slow");
    });
    .lead {
      height: 20px;
      width: 20px;
      background-color: grey;
      margin: 10px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="lead"><div class="normaldiv">1</div></div>
    <div class="lead"><div class="normaldiv">2</div></div>
    <div class="lead"><div class="normaldiv">3</div></div>
    <div class="lead"><div class="normaldiv">4</div></div>

    Note: CSS added for better visibility.

◀ Go back