Given the following html:
<div id='foo'>
<div class='prodbar'>
<div class='title'>Group 1</div>
<div class='product'>Product #1</div>
<div class='product'>Product #2</div>
<div class='product'>Product #3</div>
<div class='product'>Product #4</div>
</div>
<div class='prodbar'>
<div class='title'>Group 2</div>
<div class='product'>Product #5</div>
</div>
<div class='prodbar'>
<div class='title'>Group 3</div>
<div class='product'>Product #6</div>
<div class='product'>Product #7</div>
</div>
</div>
I have code that adds the class 'selected' to any product that is clicked. After some products are selected, the user can click a button which removes the selected products from the screen, which is simply:
$(".selected").remove();
Now, if that empties a product group, I’d like the div surrounding the group div to be removed as well. So in the above example, if Product #5 is selected and removed, I want the prodbar that now has nothing but a title to be removed with it.
I know I can accomplish what I want with a loop, but I was hoping for something more jQuery-elegant. Essentially, I need to know if a div has only 1 child. I’m fairly new to jQuery and I’m not sure if this is doable directly in the selectors. Any ideas?
If you looking for a clean up code then below will filter all prodbar and removes if title is the only children,
DEMO