J86
J86

Reputation: 15237

Replacing Nodes Error. The node to be replaced is not a child of this node

I can't see what I am doing wrong. I am getting a bunch of select lists (drop downs) and want to replace them with a <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 is giving me the error:

Uncaught NotFoundError: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.

I can't see how that can be the case! I am grabbing the parent, so it must be a child!

What am I doing wrong?

Upvotes: 19

Views: 22845

Answers (2)

Gibolt
Gibolt

Reputation: 47127

currentSelectList.replaceWith(newNode)

Use modern vanilla JS! Way better/cleaner than before. Generic form:

target.replaceWith(element);

developer.mozilla.org

Can I Use - 94% May 2020

Upvotes: 15

Eternal1
Eternal1

Reputation: 5625

In replaceChild, the new node is the first argument, not the second. You have them backwards.

parentNode.replaceChild(newNode, currentSelectList);

Also, why would you do i--? Isn't that creating an infinite loop?

Upvotes: 36

Related Questions