简体   繁体   中英

jquery replaceWith not working on google chrome

I am facing a strange problem with dynamically replacing controls using javascript in Google Chrome. The replaced controls dont show up in UI but when i use developer tools i am able to locate the replaced element but it does not show up until i close the developer tools. once i open and close developer tools the issue is no longer replicatable until i refresh the page.

This happens only in cases where i am trying to replace outerHTML of an element.

I first tried using jquery's replaceWith api, that dint help so i switched to the following script -

function chromeOuterHTML(oldElem, outerhtml)
{
var el = document.createElement('div');
el.innerHTML = outerhtml;
var parentNode = oldElem.parentNode;
var range = document.createRange();
        range.selectNodeContents(el);
        var documentFragment = range.extractContents();
        parentNode.insertBefore(documentFragment, oldElem);
        parentNode.removeChild(oldElem);
}

I dont think that its a problem with my javascript since the problem is specific to chrome and also happens in only certain cases.

Any help would be greatly appreciated

More a diagnostic tool than a solution, but have you tried delaying your insertBefore?

function chromeOuterHTML(oldElem, outerhtml)
{
var el = document.createElement('div');
el.innerHTML = outerhtml;
var parentNode = oldElem.parentNode;
var range = document.createRange();
        range.selectNodeContents(el);
        var documentFragment = range.extractContents();
            setTimeout(function () {    
                parentNode.insertBefore(documentFragment, oldElem);
                parentNode.removeChild(oldElem);
    }, 1);
}

In some situations (that I don't fully understand), DOM manipulations can fail if they happen in too quick a succession. This modification will delay (only by 1ms) the insert - it's possible that it will make a difference. It's also possible it'll do nothing!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM