Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 893
J86 Avatar asked Feb 07 '14 12:02

J86


People also ask

How do you change a child's element?

Use Node. replaceChild() to replace a child element of a node by a new element.

Which of the following methods replaces the specified child element of the current element with a new element?

The replaceChild() method replaces a child node with a new node.

How do you replace an element in a dom?

To replace a DOM element in the DOM tree, you follow these steps: First, select the DOM element that you want to replace. Then, create a new element. Finally, select the parent element of the target element and replace the target element by the new element using the replaceChild() method.


2 Answers

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?

like image 154
Eternal1 Avatar answered Oct 12 '22 22:10

Eternal1


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

like image 28
Gibolt Avatar answered Oct 13 '22 00:10

Gibolt