Jquery - Get id of nearest div?

Hi, I have a table with a list of cars

<table> <tr class="${(i % 2) == 0 ? 'odd' : 'even'}" id ="rows"> <td> <div class="check_box_div"> <div class="check_box_list"> <g:checkBox id = "isActive_${i}" class="isActive" name="isActive" value="${vehicleInstance?.isActive}" /> <input type="hidden" value="${vehicleInstance?.id}" class="vehicleId" name="vehicleId" id="isActive_${i}_" /> </div> <div class="display_image" id ="display_image_${i}"></div> </div> </td> </tr> 
Table

has many lines I want to get a div identifier, where the class name is " display_image " for each line, I tried to get it as

  $(".isActive").click(function() { var checkBox_id = $(this).attr("id"); var checkbox = $('#'+checkBox_id); var div_id =$('#'+checkBox_id).closest("div").find(".display_image").attr("id"); // always returns div_id =display_image_0(div id of first row) 

This works for the first row, but for the second row it also returns an id div for the first row only, what change should I make to get the id div in each row

+7
source share
5 answers

Go up until you find the line, and then down again to find the displayed image:

 $(".isActive").click(function() { var div_id = $(this).closest('tr').find('.display_image').attr(id); // ... }); 

Note that this does not depend on your original element identifier at all - just the layout of your elements inside the DOM.

More optimal solutions are possible, but they will work regardless of the relative positions of the .isActive and .display_image on each line.

+15
source

closet will not work here ... just as I know that the closet works with respect to the parent hierarchy.

try this one

 var div_id =$('#'+checkBox_id).parents(".check_box_div").find(".display_image").attr("id"); 
0
source

Try it.

  $(".isActive").click(function() { var div_id = $(this).parents(".check_box_list").next(".display_image").attr("id"); } 

I used parents, not parents, in case you change any of your markup.

0
source

Using

 $(".isActive").click(function() { var $row = $(this).closest("tr"); var $div_id = $row.find("div.display_image").attr("id"); }); 

jsFiddle: http://jsfiddle.net/5TV9A/8/

0
source

You can save all the information in an array and process them after the loop.

 $(".isActive").click(function() { var checkBox_id = $(this).attr("id"); var checkbox = $('#'+checkBox_id); var div_array = new Array(); $('.display_image').each(function(index) { var div_array[index] = //whatever you want; }); // Now in div_array you have stored all the information you want (the id as well) 

Hope this helps

0
source

All Articles