Change tagname of elements

by Csaba Hellinger

HTML

<div id="content">
    <span style="color:blue;">
        <p style="font-size:20px;">SOME TEXT HERE</p>
        <p style="font-size:16px;">SOME TEXT HERE</p>
    </span>
</div>

<br/>
<button id="convert">Convert</button>

CSS

p {
    padding: 10px;
    background-color: #DDD;
}

span {
    border: 1px solid red;
    display: inline-block;
}

JavaScript

// this converts an element to another tag
function replace(thisWith, that) {
    $(thisWith).replaceWith(function() {
        var i, replacement = $('<' + that + '>').html($(this).html());
        for (i = 0; i < this.attributes.length; i++) {
            replacement.attr(this.attributes[i].name, this.attributes[i].value);
        }
        return replacement;
    });
}

$("#convert").click(function convertClick() {
    // get SPANs that has Ps inside
    var $spans = $("#content span").has("p");
    $spans.each(function () {
        // change children Ps into SPANs
        replace($(this).children("p"), "span");
        // change parent SPAN into P
        replace(this, "p");        
    });
});