Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Find next Element with same class

Tags:

html

jquery

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"

});
like image 694
Zwen2012 Avatar asked Apr 29 '16 05:04

Zwen2012


Video Answer


2 Answers

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

like image 137
Kartikeya Khosla Avatar answered Nov 02 '22 07:11

Kartikeya Khosla


A technique that won't break if you change the structure of the HTML is to:

  1. Use .index() to find the container in a list of all the containers
  2. Increment the index
  3. Call .eq() to select the next container regardless of where it is in the DOM

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
screenshot

like image 38
Dem Pilafian Avatar answered Nov 02 '22 07:11

Dem Pilafian