user3029612 user3029612 - 6 months ago 21
Javascript Question

How to delete current element if previous element is empty in jquery?

I want to delete element with class "tehnicneinfo" but only if the element I'm checking ( with class "h2size") has no child. I have a bunch of those elements, generated by a plugin and I want to delete only the ones that have the next element without child. I wrote jquery code, but it delets all of my elements, not only the ones that have the next element without child. Here is my jquery code:

$('.news .h2size > div').each(function() {
var ul = $(this).find('ul');
if(!ul.length) $(this).remove();
var h1 = $('.news').find('.tehnicneinfo');
var h2size = $('.news').find('.h2size');
if(h2size.prev().is(':empty'));
{
h1.remove();
}
});


this code is inside
$(document).ready(function()
. Can you tell me what I'm doing wrong? The code is for something else also, so I'm having truble only from
var h1 = $('.news').find('.tehnicneinfo');
this line on. Thanks in advance!

Html:

<div class="news">
<h1 class="tehnicneinfo">xxx</h1>
<div class="h2size">
<div id="xyxyxy">
.......
</div>
</div>
<h1 class="tehnicneinfo">yyy</h1>
<div class="h2size"></div>
....
</div>


That's the html, only that there is like 20 more lines that are the same, but with different values (not yyy and xxx). I would need to delete all 'yyy' (they are not all with same value).

Answer

You can use filter to filter the ones you want to remove then remove them

"I want to delete only the ones that have the next element without child"

$('.tehnicneinfo').filter(function(){
    return !$(this).next().children().length; 
    // only ones with next sibling with no children
}).remove();

JSFIDDLE