Question

I'm receiving HTML data from an application but i need to change some nodes to make it compatible with a new app, like change <b> to <strong>.

I wrote this example http://jsfiddle.net/daYL4/9/.

What I wanted to do is check all nodes of the div, and convert them if needed, but it seems to not work properly. When i press the button, only the div primary children are changed. If I press the button again, children of children are changed, etc. I don't understand why it doesn't change all nodes on the first click.

This is what i get:

<font>span
    <b>bbb<i>iii</i>bbb<i>iii</i>bbb<i>i<font>font</font>ii</i></b>
</font>

And this is what I want when pressing the button :

<span>span
        <strong>bbb<em>iii</em>bbb<em>iii</em>bbb<em>i<span>font</span>ii</em></strong>
    </span>

Does anyone have a clue?

Was it helpful?

Solution

Something like this?

 //create a jquery function for ease of operation.
$.fn.transform = function(replacer){
    replacer = replacer || {};
    this.find('*').each(function(){
        var newNode = replacer[this.nodeName];
        if(this.nodeType == 1 && newNode){//check for element node and if it is one in the replacement object
            $(this).contents().unwrap().wrapAll(newNode); // take the contents out of the element unwrap it and then wrap all of the contents by creating a new object based on the replacement object value.
        }
    });
    return this; //return for chaining
}

$(document).ready(function() {
    $("button").click(function() {

        //create an object with key value pair of replacement required
        var repl = {
            'B' :'<strong/>',
            'I' : '<em/>',
            'FONT': '<span/>'
        }
        $("div").transform(repl);
    });    
});

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top