afif
afif

Reputation: 1

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

I can't find the problem in my code could someone please help on this issue? Here's my source code

<button onclick="myfunction()" class="button" id="btw1" > Voir numéro   </button>

<script type=text/javascript> 
            function myfunction(){
           
            var bouton= document.getElementById('btw1');
           
             var parent= document.body;

            var nvbtw = document.createElement('btw2');
            nvbtw.id='btw2';
            nvbtw.innerHTML='<button  class="button" id="btw2" > (+33 00 00 00 00 00)   </button>';
            
            parent.replaceChild(nvbtw,bouton);
}</script>

What I want to do is a hidden button number like when you click on it it shows the number.

Upvotes: 0

Views: 745

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074555

The error message is telling you that bouton is not a direct child of document.body. Instead of var parent = document.body, use:

var parent = bouton.parentElement; // or `.parentNode`

Side note: If you're targeting modern browsers, you may find replaceWith easier to work with:

bouton.replaceWith(nvbtw);

(It can also be polyfilled for older browsers.)

Upvotes: 1

Related Questions