S Blasko S Blasko - 1 month ago 7
Javascript Question

Find an HTML element next to specific closing tag

I'm looking to see if the last

<hr>
tag within the parent
<main>
exists directly before the closing
</main>
tag.

So in the following, the
<hr>
tag that is last within the
<main>
tag, directly before a closing
</main>
tag is the one targeted:

<main>
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem
</div>
<hr class="container" />
</main>


Although the
<hr>
should not be removed if, for example, there is a
<div>
tag in front of it:

<main>
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem
</div>
</main>

Answer

You can filter the HR elements based on whether or not they are the last child of the same parent

$('hr').filter(function() {
    return this === this.parentNode.lastElementChild;
}).remove();

FIDDLE

Or target any HR elements that are also the last child

$('main hr:last-child').remove();