I have an element with text, spans and anchors and I want to remove everything except a specific span inside it. This is the html And the jQuery I used:
jQuery(function($) {
$('.post-meta').contents(':not(".published")').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p class="post-meta">door <span class="author vcard"><a></a></span> | <span class="published">10 september, 2021</span> | <a>Nieuws</a>,
<a></a>,
<a></a> | 0 reacties</p>
And the output after the jQuery ran:
<p class="post-meta">door | <span class="published">10 september, 2021</span> | , , | 0 reacties</p>
So it removes all elements but leaves the loose text inside the p.