What is the best way to update all HTML content using Javascript?

After attempting to use

$("html").html(this.responseText);
, I found that it successfully replaced the content but did not replace the head and body tags.

For instance, if I intended to replace the following 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>

The result when inspecting my HTML structure was as follows:

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

<h1>This is a Heading</h1>

<script>...</script>

</html>

This caused issues with my CSS. Removing the scripts resolved the issue. Is there a solution to this problem?

I also attempted a JavaScript approach like so:

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

However, this led to syntax errors with redeclaration in my JavaScripts.

The actual code where I tried to implement this is shown below:

<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>

Answer №1

As previously mentioned, this task is achievable

document.querySelector('body').innerText = 'hello world';

However, if you require HTML to be displayed, the following approach should be taken

document.querySelector('body').innerHTML = '<p>hello world</p>';

Answer №2

When using the Chrome browser, I discovered that in order for the response (or any innerHTML you want to use as the new page) to display correctly, it must begin strictly with the <head> tag. It cannot start with <html>, <!DOCTYPE html>, or anything else. Otherwise, replacing innerHTML or using document.write(response) will always output the entire content within the <body>...</body> tags.

Below is a snippet/page that I used locally to test various suggestions that I came across (none of which worked), until I condensed 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>

Answer №3

JavaScript: Using the innerHTML property allows you to replace all HTML content within an element.

document.querySelector('body').innerHTML = '...'

jQuery:

$( document ).ready(function() {
  $('body').html('...');
});

Answer №4

search for tag content within a given string:

function findTagContent(tagname,htmlText) {
  var tagHtml = $(htmlText).find(tagname).html();
  return tagHtml;
}

swap the head and body contents with the body and head respectively in your output:

$("head").html(findTagContent("head",this.responseText));
$("body").html(findTagContent("body",this.responseText));

Answer №5

I have confirmed that the following code is functional...

let responseTxt="<html> \
<head><title>changed hello</title></head><body><h1>Changed body</h1></body></html>"
$(document).ready(()=>{
 $(".action").click(()=>{
  $("html").html(responseTxt)
 });

});
<html>
<head><title>hello</title></head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
<h1>hello</h1>
<button class="action">Change HTML</button>
</body>
</html>

Answer №6

Responding to the comment by Dima Pavlenko. Yes, this solution does indeed function.

document.addEventListener("DOMContentLoaded", (e) => {
  document.querySelector("#replace-content-btn").addEventListener('click', function() {
    document.write(`
      <html>
        <head>
          <title>New Page Title</title>
        </head>
        <body>
          <p>New body content.<br>Inspect the head element!</p>
        </body>
      </html>`);
  });
});
<html>
  <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>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Performing a fetch() POST request in Express.js results in an empty body object being generated

Purpose: Implement a function in fetch() to send specified string data from the HTML document, for example "MY DATA" Here is the code snippet: HTML Code: <!DOCTYPE html> <html> <body> <script type="text/javascript"> function ...

Developing a right triangular prism with Three.js

I am working on creating a right triangular prism. Here is the current code I have: var triangleGeometry = new THREE.Geometry(); triangleGeometry.vertices.push(new THREE.Vector3(-1.0, 1.5, 0.95)); triangleGeometry.vertices.push(new THREE.Vector3(-1.0, ...

Update the background color of an li element upon clicking

Is there a way to change the background color upon clicking on the li anchors? <div class="text-center row"> <ul class="col-md-12 secondNav"> <li class="navbar-brand nav-item" style="margin-right: 9%"> <a href="#" >& ...

Connecting Documents Together

I'm looking to learn how to link files together, specifically creating a button that when clicked takes you to another site or the next page of reading. I apologize if this is a simple question, as I am new to coding and only familiar with password-ba ...

The CSS styles on pages dynamically adjust as new content loads with the use of Infinite Scroll functionality

I am facing an issue with my site that has Infinite Scroll, Isotope, and .mb_miniplayer_play audio player. Whenever a new page is loaded in, the CSS on previously loaded pages changes for one element only. Despite trying different solutions, I can't s ...

Problem with Flickity's is-selected feature

I am currently exploring Flickity and its functionality. I have a carousel that auto-plays, with the selected cell always placed in the middle and highlighted with a grey background. However, I would like to customize it so that the selected cell is positi ...

Is it possible to remove individual items from a FlatList by clicking on them and updating the state?

I have a FlatList displaying items from an array called data. My goal is to remove each item individually by clicking on it, but currently when I click on one item, all items are deleted at once. Any suggestions on how to address this issue? Here's ...

How to Align Two HTML Forms Using CSS

I've been experimenting with various methods, but I'm still unable to achieve the desired outcome. Currently, my setup looks like this: https://i.sstatic.net/fUXKr.png However, what I really want is something more like this: https://i.sstatic ...

Unable to transmit HTML emails

I've been encountering an issue while trying to send HTML emails using Gmail SMTP from CI. It seems that my emails are being rejected if they contain any tables. Interestingly, there is no error message provided; the emails simply do not show up in my ...

What is the best way to send a POST request to a certain URL using Axios in a React application?

I am facing a challenge with making a post request to a rather complex URL: http://localhost:8080/api/login?email=example%40gmail.com&password=examplepassword as per the Swagger-UI documentation. The examples on axios's GitHub page mention that th ...

initiating angular and node individually but with integration between them

For testing purposes in production, I needed to separate my angular 1.x frontend client and node backend server code. Both the client and server use API functions provided by node, but they are running on different servers on my local machine. My node serv ...

Inserting text into a textarea and watching it disappear

<textarea class="skinCondition-field vlongtext clear ui-input-text ui-body-d ui-corner-all ui-shadow-inset" type="text" placeholder="Share details of your current skin condition (e.g. normal, dry, flaky, etc). Optionally, mention any past skin issues, m ...

Is {{@index}} an even or odd number in Handlebars: A Step-by-Step Guide

I'm currently cycling through an array, and I'd like to adjust the background color of the div based on whether the current index is odd or even. Unfortunately, when I try to use {{@index}} within an if statement in Handlebars, like so: {{#each ...

Tips for maintaining the dropdown selection when new rows or columns are added to a table

I have a task requirement where I must generate a dynamic table using jQuery. I've successfully implemented adding dynamic columns or rows to the table. Feel free to check out the fiddle code here. HTML: <div id='input_div' name='i ...

Accessing feedback from Reddit's API

After writing some code to search Reddit's API with a specific query, I now want it to display comments as well. Inside my $.getJSON statement that retrieves each title/post based on the search query, I have the following nested code block. The goal i ...

What exactly powers Angular JS behind the scenes?

I have recently embarked on my journey to learn Angular JS. Despite this, I find myself struggling to grasp a deep understanding of how Angular actually operates internally. Take for example the w3schools' initial sample: <script src="https://aj ...

Combining items from the identical array in pairs using distinct identifiers

I have an array containing double values. const data = [ -0.003,-8.178509172818559E-16, 0.002,-1.3576469946421737E-15, 0.007,-1.2329107629591376E-1] I am looking to utilize these values in react-vis. The necessary syntax for data insertion in react-vis ...

Change glb files to draco glb in the frontend

Can we encode and transform glb files into draco glb format using only frontend technologies (client side)? ...

Toggle the visibility of each item in the list using jQuery

I am trying to update the innerHTML property of a div element for each name in a list and animate it using fadeIn, delay for a specific time, and fadeOut. <div id="welcomeBox">Welcome SOMETHING</div> var list = ["George","Bob","Tom"]; $.each ...

Scraping specific section of text from a webpage's source code with BeautifulSoup library in Python

As a novice in python, I have little to no knowledge of HTML. After stumbling upon a captivating youtube video (https://www.youtube.com/watch?v=kEItYHtqQUg&ab_channel=edureka%21) on web scraping, I became intrigued by the idea of extracting text from U ...