Remove content from element except specific inner span with jQuery

Viewed 61

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.

1 Answers

Try this

jQuery(function($) {
  $('.post-meta').html(function() { return $(this).find(".published").html()})
});
<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>
  
  <p class="post-meta">door <span class="author vcard"><a></a></span> | <span class="published">11 september, 2021</span> | <a>Nieuws</a>,
  <a></a>,
  <a></a> | 0 reacties</p>

Related