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?
Use Node. replaceChild() to replace a child element of a node by a new element.
The replaceChild() method replaces a child node with a new node.
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.
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?
Use modern vanilla JS! Way better/cleaner than before. Generic form:
target.replaceWith(element);
developer.mozilla.org
Can I Use - 94% May 2020
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With