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
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 ofnext()
to find all thenext-container
elements that are siblings of the parent container of the clicked element:You have to wrap all your element in a div. Adding class name will be considered static code and not dynamic.