JS. How to replace html element with another element/text, represented in string?

As the Jquery replaceWith() code was too bulky, tricky and complicated, here’s my own solution. =)

The best way is to use outerHTML property, but it is not crossbrowsered yet, so I did some trick, weird enough, but simple.

Here is the code

    var str="<a href="http://www.com">item to replace</a>"; //it can be anything
    var Obj = document.getElementById('TargetObject'); //any element to be fully replaced
    if(Obj.outerHTML) { //if outerHTML is supported
        Obj.outerHTML=str; ///it's simple replacement of whole element with contents of str var
    }
    else { //if outerHTML is not supported, there is a weird but crossbrowsered trick
        var tmpObj=document.createElement("div");
        tmpObj.innerHTML='<!--THIS DATA SHOULD BE REPLACED-->';
        ObjParent=Obj.parentNode; //Okey, element should be parented
        ObjParent.replaceChild(tmpObj,Obj); //here we placing our temporary data instead of our target, so we can find it then and replace it into whatever we want to replace to
        ObjParent.innerHTML=ObjParent.innerHTML.replace('<div><!--THIS DATA SHOULD BE REPLACED--></div>',str);
    }

That’s all

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)