You can use filter()
to select only the .test > h2
elements which have no following siblings, and then remove them:
$(".test > h2").filter((i, el) => $(el).next().length == 0).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">
<h2>This will be removed</h2>
</div>
<div class="test">
<p>Lorem ipsum</p>
<h2>This will also be removed</h2>
</div>
<div class="test">
<p>Dolor sit</p>
<h2>This will NOT be removed</h2>
<p>Amet consectetur</p>
</div>
Use find
to search for children elements.
Your current condition would prevent your from removing it since you’re checking if there are no children. In your case, there would be children.
$(".test").each(function() {
const h2 = $(this).find('h2');
if(h2.siblings().length === 0) { //check for siblings
h2.remove()
}
});
If the <h2>
is always your first children you can use $(".test:not(:has(> h2 + *))").empty();
$(".test:not(:has(> h2 + *))").empty();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">
<h2>Dosen't Have sibilings</h2>
</div>
<div class="test">
<h2>Has sibilings</h2>
<p>Amet consectetur</p>
</div>
I was wondering if there is a way to just remove the <h2>
element inside of an element with a particular class if that element doesn’t have any other elements following it. For example if I have only the following:
HTML:
<div class="test">
<h2>Test</h2>
</h2>
I want to just remove the <h2>Test</h2>
but keep the div element present.
jQuery:
$(".test").each(function() {
if($(this).children().length == 0) {
$(this).remove();
}
});
Elements, not tags. Tags are text in your markup file.