Search code examples
jqueryhtml

jQuery: Find next Element with same class


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"

});

Solution

  • 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