Error replacing nodes. The replacement node is not a child of this node.

I do not see what I am doing wrong. I get a few selection lists (dropdowns) and want to replace them with <span>, so here is my code:

var selectListElements = document.getElementsByTagName('SELECT');

//select elements
for (var i = 0; i < selectListElements.length; i++) {
    var currentSelectList = selectListElements[i];

    //alert(selectListElements[i].name);
    if (currentSelectList.dontReplace != 'true') {
        var newNode  = document.createElement('SPAN');
        var nodeText = currentSelectList.options[currentSelectList.selectedIndex].value;
        var parentNode = currentSelectList.parentNode;
        parentNode.replaceChild(currentSelectList, newNode);
        i--;

        newNode.innerText           = nodeText;
        newNode.className           = 'tableBody';
        newNode.style.verticalAlign = 'top';
    }
}

But this gives me an error:

Uncaught NotFoundError: failed to execute replaceChild on the node: the replaced node is not a child of this node.

I do not understand how this could be so! I grab the parent, then it must be a child!

What am I doing wrong?

+9
source share
2 answers

The replaceChildnew node is the first argument, not the second. You have them back.

parentNode.replaceChild(newNode, currentSelectList);

, i--? ?

+14

currentSelectList.replaceWith(newNode)

JS! /, . :

target.replaceWith(element);

developer.mozilla.org

- 92% 2019

+6

Source: https://habr.com/ru/post/1525784/


All Articles