Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace entire HTML content with Javascript?

I tried to use $("html").html(this.responseText);. Which replaces the content but it does not replace the head and body tags.

So for example if i want replace this content:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>...</script>
<script>...</script>
</head>
<body>

<h1>This is a Heading</h1>


<script>...</script>
</body>
</html>

Then i check my HTML structure in inspector, and the result this:

<!DOCTYPE html>
<html>
<title>Page Title</title>
<script>...</script>
<script>...</script>

<h1>This is a Heading</h1>

<script>...</script>

</html>

And it messed my css so. I have tried without scripts, and it worked fine. What is the solution for this problem?

I have also tried with javascript approach

document.open();
document.write(this.responseText);
document.close(); 

But it confuses my javascripts. I am getting redeclaration syntax error.

My real code where i want to implement:

<script>
  
        var frm = $('#frm');
        var submitActors = frm.find('input[type=submit]');
        var submitActor = null;
        submitActors.click(function(event) {
                submitActor = this;  
        });
        
        frm.unbind('submit').submit(function () {
           
            var formAction = document.getElementById("frm").getAttribute('action'); // Get the form action.
            var data = "";
            var pageUrl = "";
            var test_uuid = "";
            var test_number = "";
            var qid = JSON.parse(sessionStorage.getItem('userChoice')).qid;
            
            
            
            if(submitActor.name == "cmdSave"){
                data = {
                    "cmdSave" : $("#cmdSave").val(),
                    "Answer": document.querySelector('input[name="Answer"]:checked').value,
                    "csrfmiddlewaretoken": document.querySelector('input[name=csrfmiddlewaretoken').value,
                    "qid": qid
                }
            }
            else if(submitActor.name == "cmdNext"){
                data = {
                    
                    "cmdNext": document.querySelector('#cmdNext').value,
                    "csrfmiddlewaretoken":document.querySelector('input[name=csrfmiddlewaretoken').value,
                    "qid": qid
                }
            }
            var httpRequest = new XMLHttpRequest();
            var formData = new FormData();
            
            
            
            Object.keys(data).forEach(function(key) {
                console.log(key, data[key]);
                formData.append(key, data[key]);
            });
                console.log(formData)
            httpRequest.onreadystatechange = function(){
                if ( this.readyState == 4 && this.status == 200 ) {
                var response = this.responseText;
                    console.log(this.responseText) // Display the result inside result element.

                    // 1.Option
                    {% comment %} document.open();
                    document.write(this.responseText);
                    document.close(); {% endcomment %}
                    
                    // 2.Option
                    
                    {% comment %} document.documentElement.innerHTML = this.responseText;  {% endcomment %}
                    
            
                    // 3.Option
                    $(document).ready(function(){
                        $("html").html(response);
                    });
                                                                             
                
                    test_number = document.getElementById("lblNrCrt").textContent;  
                    test_uuid = "{{test.uuid}}";
                    pageUrl = "/intro/" + test_uuid + "/" + test_number + "/";
                    window.history.pushState('', '', pageUrl);
                }
            };

            httpRequest.open("post", formAction);
            httpRequest.send(formData);

            return false;
        
        });

</script>

like image 714
Arnold96 Avatar asked Aug 29 '26 16:08

Arnold96


2 Answers

As I pointed out it can be done

document.querySelector('html').innerText = 'yolo';

But if you need to render HTML you should do

document.querySelector('html').innerHTML = '<div>yolo</div>';
like image 198
Jeanluca Scaljeri Avatar answered Aug 31 '26 07:08

Jeanluca Scaljeri


Using Chrome browser I found that the response (or any innerHTML you want to use as the new page) has to start strictly with the <head> tag. Not <html> or <!DOCTYPE html> or anything else, otherwise replacing innerHTML or using document.write(response) always outputs the whole content inside <body>...</body> tag.

Here is the snippet/page I used locally to try all suggestions I saw (and didn't work), until I tried condensing the new page content/string to "<head>...</head><body>...</body>".

document.querySelector("#replace-content-btn").addEventListener('click', function() {
  document.querySelector("html").innerHTML = `
    <head>
      <title>New Page Title</title>
    </head>
    <body>
      <p>New body content.<br>Inspect the head element!</p>
    </body>`;
});
<head>
  <title>Some Page Title</title>
</head>

<body>
  <p>Some body content.<br>Inspect the head element before and after button click.</p>
  <button type="button" id="replace-content-btn">Replace entire HTML</button>
</body>
like image 42
Dima Pavlenko Avatar answered Aug 31 '26 05:08

Dima Pavlenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!