Reputation: 133
Trying to loop through some elements and delete their parent div holder if it is found to be empty. I am using the following jquery code and for some reason, it only removes the first matched element and none after this.
$('.sylsection p').each( function() {
if ( $(this).text() == '' ) {
$(this).closest('.sylsection').remove();
}
});
Any ideas on why this is happening?
HTML structure is something like:
<div class="sylsection">
<h6>Content</h6>
<hr>
<p>Content</p>
</div>
<div class="sylsection">
<h6></h6>
<hr>
<p></p>
</div>
<div class="sylsection">
<h6>Content</h6>
<hr>
<p>Content</p>
</div>
<div class="sylsection">
<h6></h6>
<hr>
<p></p>
</div>
<div class="sylsection">
<h6>Content</h6>
<hr>
<p>Content</p>
</div>
<div class="sylsection">
<h6></h6>
<hr>
<p></p>
</div>
Don't mind the in html markup. Will move that to an external css file later.
Cheers
Upvotes: 1
Views: 2529
Reputation: 14179
I tried to execute the code with jQuery 1.12.4 (https://code.jquery.com/jquery-1.12.4.min.js) and it seems to work properly, see this jsfiddle: https://jsfiddle.net/0Lbp8xL1/3/
The function and the html is the same:
$('.sylsection p').each( function() {
if ( $(this).text() == '' ) {
$(this).closest('.sylsection').remove();
}
});
Upvotes: 1
Reputation: 1740
Works fine:
$('.sylsection p').each(function () {
if ($(this).text() == '') {
$(this).closest('.sylsection').remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sylsection">
<h6>Content 01</h6>
<hr>
<p>Content 02</p>
</div>
<div class="sylsection">
<h6>Header 01</h6>
<hr>
<p></p>
</div>
<div class="sylsection">
<h6>Content 03</h6>
<hr>
<p>Content 04</p>
</div>
<div class="sylsection">
<h6>Header 02</h6>
<hr>
<p></p>
</div>
<div class="sylsection">
<h6>Content 05</h6>
<hr>
<p>Content 06</p>
</div>
<div class="sylsection">
<h6>Header 03</h6>
<hr>
<p></p>
</div>
Upvotes: 2