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

后端 未结 8 1035
清酒与你
清酒与你 2020-12-24 03:03

I have a problem with replacing html elements.

For example, here is a table:

0
8条回答
  •  无人及你
    2020-12-24 03:45

    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 = 'item to replace'; //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='';
        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('
    ',str); }

    That's all

提交回复
热议问题