skip to Main Content

I’m trying to select the next element to the parent div of my target element when it’s clicked, but it only works once and there are several of them in the page, all with the same class. Below you can find my code. I would really appreciate some help here.

It only works for the first element of the page, not for the rest.

$(document).ready(function() {
  $(".element").click(function() {
    $(this).parent().next().slideToggle();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent-container">
  <p class="element">Target element 1</p>
</div>

<div class="next-container">Next element 1</div>

<div class="parent-container">
  <p class="element">Target element 2</p>
</div>

<div class="next-container">Next element 2</div>

<div class="parent-container">
  <p class="element">Target element 3</p>
</div>

<div class="next-container">Next element 3</div>

2

Answers


  1. If I understand well what you want, $(this).parent().next() will always return the immediate next sibling of the parent container of the clicked element.

    Try to use the siblings() method instead of next() to find all the next-container elements that are siblings of the parent container of the clicked element:

    $(document).ready(function() {
      $(".element").click(function() {
        $(this).parent().siblings(".next-container").slideToggle();
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="parent-container">
         <p class="element">Target element</p>
    </div>
    <div class="next-container">
      First
    </div>
    <div class="next-container">
      Second
    </div>
    <div class="next-container">
      Third
    </div>
    Login or Signup to reply.
  2. You have to wrap all your element in a div. Adding class name will be considered static code and not dynamic.

    $(document).ready(function() {
      $(".element").click(function() {
        $(this).parent().next().slideToggle();
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="parent-container">
         <p class="element">Click here</p>
    </div>
    <div class="next-wrapper">
      <div class="first-container">
        Alpha
      </div>
      <div class="second-container">
        Beta
      </div>
      <div class="third-container">
        Gamma
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search