Search code examples
jquerywordpressblogs

How do I replace a heading tag with a link inside while preserving the link?


I am developing a WordPress blog and my client wants to remove all of the H3 headings from the article sidebar (Related Posts - don't ask). I have found this solution to replace the H3 tag with a SPAN in my example below. The issue is that the link inside also gets removed. The link is not hard-coded, so the heading tag needs to be replaced while preserving the HTML inside of it. Any thoughts?

$(".blog-sidebar h3.entry-title").replaceWith(function () {
     return "<span class='sidebar-post-title'>" + $(this).text() + "</span>";
});

This is the current structure of the Sidebar Articles

<h3 class="entry-title">
     <a href="https://website.com/article-name/" target="_self">Article Name</a>
</h3>

Solution

  • Try out

      $(".blog-sidebar h3.entry-title").replaceWith(function () {
             return "<span class='sidebar-post-title'>" + $(this).html() + "</span>";
        });