I want the next Element with the same class. So I have a click action on the class "calculationContainer". When I click this element, I want to have access of the next element with the class "calculationContainer". But all I tried doesn't work. Maybe someone can help me with this?
I have this HTML Code:
<div class="body">
<div class="inner">
<div class="calculationContainer">
<div class="element">
<input type="text" id="name1">
</div>
</div>
</div>
</div>
<div class="body">
<div class="inner">
<div class="calculationContainer">
<div class="element">
<input type="text" id="name2">
</div>
</div>
</div>
</div>
<div class="body">
<div class="inner">
<div class="calculationContainer">
<div class="element">
<input type="text" id="name3">
</div>
</div>
</div>
</div>
And my jQuery:
$('.calculationContainer').on('click', function() {
var amountCalculationContainer = $(this);
var nextAmountCalculationContainer = amountCalculationContainer.next('.calculationContainer'); //<- Only finds the div with class "element"
});
Try This :-
$('.calculationContainer').on('click', function() {
var $elem = $(this).closest('div.body').next().find('div.calculationContainer')
});
Use .closest()
to traverse up and find first div.body
parent and then use .next()
to get next element and then find div.calculationContainer
with .find()
.
Handle the situation when .calculationContainer
is at last position(as shown in demo).
DEMO
A technique that won't break if you change the structure of the HTML is to:
JavaScript:
const next = (event) => {
const list = $('.calculationContainer'); //all containers
const index = list.index($(event.target)); //current container
const target = (index + 1) % list.length; //increment with wrap
const nextAmountCalculationContainer = list.eq(target);
};
$('.calculationContainer').click(next);
See if you can catch the red button:
https://jsfiddle.net/55pmmzd6/68
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With