Open In App

How to replace the entire HTML node using JavaScript ?

Given an HTML document and the job is to replace the entire HTML element by a new one with the help of JavaScript. A few approaches are discussed here.

Approach 1:



Example 1: This example implements the above approach.




<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        Replace the entire HTML node using JavaScript.
    </title>
    <script src=
    </script>
    <style>
        #div {
            background: green;
            height: 100px;
            width: 200px;
            margin: 0 auto;
            color: white;
        }
    </style>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">  
            GeeksForGeeks  
        </h1>
    <p id="GFG_UP">
    </p>
    <button onclick="GFG_Fun();">
        click here
    </button>
    <p id="GFG_DOWN" style="color: green;">
    </p>
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
        up.innerHTML = 
 "Click on the button to replace the entire HTML element.";
  
        function GFG_Fun() {
            var Str = 
'<!DOCTYPE HTML><html><head><title>Check if an element is a'+
' div in JavaScript.</title></head><body style = "text-align:center;">'+
'<h2 style = "color:green;">GeeksForGeeks</h2><p>This is replaced element.'+
                '</p></body>  </html>';
            $('html').html(Str);
        }
    </script>
</body>
  
</html>

Output:

Approach 2:



Example 2: This example implements the above approach.




<!DOCTYPE HTML>
<html>
  
<head>
    <title>
       Replace the entire HTML node using JavaScript.
    </title>
    <script src=
    </script>
    <style>
        #div {
            background: green;
            height: 100px;
            width: 200px;
            margin: 0 auto;
            color: white;
        }
    </style>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">  
            GeeksForGeeks  
        </h1>
    <p id="GFG_UP">
    </p>
    <button onclick="GFG_Fun();">
        click here
    </button>
    <p id="GFG_DOWN" style="color: green;">
    </p>
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
        up.innerHTML = "Click on the button to replace the entire HTML element.";
  
        function GFG_Fun() {
            var Str = 
                '<!DOCTYPE HTML><html><head><title>Check if an element is a div'+
                ' in JavaScript.</title></head><body style = "text-align:center;">'+
                '<h2 style = "color:green;">GeeksForGeeks</h2><p>'+
                'This is replaced element.</p></body>  </html>';
            var newHTML = document.open("text/html", "replace");
            newHTML.write(Str);
            newHTML.close();
        }
    </script>
</body>
  
</html>

Output:


Article Tags :