Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change H3 to H2 with jquery keeping href and html elemens [duplicate]

I need to change (just) the h3 tag to h2, keeping all default html elements inside, this code are erasing all html contents !!

<script type="text/javascript">
$(function () {
        $('.sideMenu h3').replaceWith(function () {
        return "<h2>" + $(this).text() + "</h2>";
    });
});
</script>

<div class="sideMenu">
    <h3 class="sapanos">
       <span></span>
       <a href="#" title="Sainos">Sapanos</a>
    </h3>
</div>
like image 580
user2087563 Avatar asked Mar 16 '23 04:03

user2087563


1 Answers

Use .html() to keep all the HTML structure. text() just gets the plain text, and throws away all the tags.

$('.sideMenu h3').replaceWith(function () {
  return "<h2>" + $(this).html() + "</h2>";
});

To keep the classes, do:

$('.sideMenu h3').replaceWith(function() {
  return $("<h2>", {
    class: this.className,
    html: $(this).html()
  });
});

like image 140
Barmar Avatar answered Mar 30 '23 00:03

Barmar