Change H3 to H2 while maintaining jquery href and html elemens

I need to change the (simple) tag h3to h2, keeping all html elements by default inside, this code erases 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>
+4
source share
2 answers

Use .html()to save the entire HTML structure. text()just receives plain text and discards all tags.

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

To save classes, do:

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

+4
source

Problem in

return "<h2>" + $(this).text() + "</h2>";

.text()Use instead .html().

.text() gets only text content.

.html() gets the html content you want to pass.

0
source

All Articles