Add HTML for first empty div in parent

I searched here for a while, but can’t find anything about this. I have a set of divs in the parent div. When the user clicks the compare flag, I want to add HTML containing the data thumbnail to the first empty div. Therefore, if the user clicks on three things for comparison, the first will go to div1, the second to div2, and so on. I want to do this in jQuery.

Below is what I have:

<div id="my_cars_compare" class="my_cars_expanded" style="height: 45px;"> <span class="my_cars_heading"> X cars added to My Cars <span class="expand_it">Expand</span> </span> <div id="my_cars_1" class="my_cars_empty first"></div> <div id="my_cars_2" class="my_cars_empty"></div> <div id="my_cars_3" class="my_cars_empty"></div> <div id="my_cars_4" class="my_cars_empty"></div> <div id="my_cars_5" class="my_cars_empty"></div> <div id="my_cars_6" class="my_cars_empty"></div> <input type="submit" value="Compare" class="btn_compare" /> <br clear="all" /> </div> 

JQuery

 $(document).ready(function() { $('.compare_click').click(function() { var dataThumbnail = $(this).parent('td').find('img.clicked').attr('data-thumbnail'); var my_cars_count = $('.my_cars_expanded').children('div').length; for ( my_cars_count >= 6 ) { $('.my_cars_expanded').find('div:empty').append('<div class="my_cars_details" style="position: relative;"><div class="my_cars_delete"><img src="btn_mycars_close_overlay.png" /></div><div class="my_cars_photo"><img src="'+dataThumbnail+'" width="67px" /></div></div>'); }; }); }); 
+8
jquery html
source share
1 answer

You can use the selector :first , div:empty selects all empty div tags:

 $('.my_cars_expanded').find('div:empty:first').append('...'); 

The syntax of your for loop is as an if , I think you want to use an if .

 var my_cars_count = $('.my_cars_expanded').find('div:empty').length; if ( my_cars_count > 0 ) { $('.my_cars_expanded').find('div:empty:first').append('...'); }; 
+10
source share

All Articles