Level breakout transform

by tomprogramming

HTML

<strong>Before:</strong>
<div id="starting">
    <span class="level2" style="font-weight:bold;">level 2 and bold</span>
    <br/>
    <span class='level2' style="">level 2 and "empty" style</span>
    <br/>
    <span class="level2">level2, no style</span>
    <br/>
    <span class="" style="font-weight:bold;">bold, "empty" class</span>
    <br/>
    <span style="font-weight:bold">bold, no class</span>
    <br/>
</div>
<strong>After:</strong>

CSS

div{
    
    margin:20px;
    padding:10px;
    border:1px solid #000;
}

.level1 { font-size:24px; }
.level2 { font-size:20px; }
.level3 { font-size:18px; }
.level4 { font-size:12px; }

JavaScript

var ending = $('<div id="ending"></div>');
var starting = $("#starting");
ending.html(starting.html());
ending.appendTo('body');


var levelTransform = function(node){
    var levels = ["level1","level2","level3","level4"], i = 0, max = levels.length, level;
    for(;i < max; i++){
        level = levels[i];
        $(node).find("." + level).each(function(){
            var $this = $(this);
            var style = $this.attr('style');
            var newLevel;
            console.log($this.html());
            console.log($this.attr('style'));
            console.log('-------');
            if (style){
                newLevel = $("<span></span>").addClass(level);
                $this.removeClass(level);
                $this.wrap(newLevel);
            }
        });
    }
    
};



levelTransform(ending);