Preserving CSS styling while loading an HTML page with InnerHTML

By using the following code snippet, I have successfully implemented a feature on my website that allows me to load an HTML page into a specific div container when clicking a link in the menu.

However, I encountered an issue where the background color of the loaded HTML page is not displaying as expected. While all other CSS elements are rendering correctly, the background color seems to be missing.

I appreciate any insights or solutions you can provide to help resolve this matter.

JavaScript code:

function processAjax(url) 
{ 
    if (window.XMLHttpRequest) { // Non-IE browsers 
        req = new XMLHttpRequest(); 
        req.onreadystatechange = targetDiv; 
        try { 
            req.open("GET", url, true); 
        }
        catch (e) { 
             alert(e); 
        } 
        req.send(null); 
    } else if (window.ActiveXObject) { // IE 
          req = new ActiveXObject("Microsoft.XMLHTTP"); 
             if (req) { 
               req.onreadystatechange = targetDiv; 
               req.open("GET", url, true); 
               req.send(); 

    } 
} 
return false; 
} 

function targetDiv() { 
    if (req.readyState == 4) { // Complete 
          if (req.status == 200) { // OK response 
              document.getElementById("containerDiv").innerHTML = req.responseText; 
          } else { 
            alert("Problem: " + req.statusText); 
          } 
    }  
}

HTML:

<a onclick="return processAjax(this.href)"  href="example.html">LOAD CONTENT</a>
<div id="containerDiv"></div>     

Answer №1

Retrieve the style element from the webpage and add it to the header section:

var styles = document.getElementsByTagName('style');
var head = document.getElementsByTagName('head')[0];

for(var x = 0; x < styles.length; x++){
    head.appendChild(styles[x]);
}

Update:

To apply the fetched HTML content as an element initially:

var div = document.createElement('div');
div.innerHTML = req.responseText;
var styles = div.getElementsByTagName('style');

for(var x = 0; x<styles.length;x++){
    document.getElementsByTagName('head')[0].appendChild(styles[x]);
}

Implement the revised code, discard the old one, and insert it within the if(reg.status == 200) condition.

Answer №2

Replace .innerHTML with .html, or opt for .load(req.responseText)

I think .innerHTML replaces all content. You only need to modify a specific section.

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

Inserting information into an array: Access the final index consistently with TypeScript

I am interested in dynamically creating a table by allocating it, with the variable nbrBoules: boules:Boule :[] boule:Boule; Boule{id,poids} Method(){ for (var _i = 0; _i < this.nbrBoules; _i++) { this.boule.id = _i; alert(_i); this ...

Utilize ng-checked in AngularJS to bind all values from an array to checkboxes

I'm working on a project where I need to bind the name and age of a person using checkboxes, with the data looped through ng-repeat. However, I seem to be able to only get the "name" from the array, not the "age". Can someone please help me find my mi ...

React - Clearing State data retrieved from axios request

I am currently facing an issue with resetting the state of an object in my users array upon clicking the delete button. Even after successfully removing the object from the database, the state does not update as intended. I have managed to verify the prese ...

Ensuring a radio button is pre-selected by default in React by passing in a prop

Assume I have a React function similar to this function Stars({handleStarClick, starClicked}) { if (starClicked === 3) { document.getElementById('star3').checked = true } return ( <div className="rate"> ...

Steps for resending an Ajax request once the previous one has been completed

Currently, I am experimenting with a basic Ajax request to a webpage by triggering it through an onclick event on a button: // 1. Create an XMLHttpRequest object var myRequest = new XMLHttpRequest(); // 2. Use the open method to request a resource from th ...

All you need to know about the properties of CSS ul

When I specify .a ul{} .a ul li{} as well as .b ul{} .b ul li{} will the properties of ul in .b be completely isolated from the properties of ul in .a? Or will they have some commonalities? I am looking to ensure that the styles for ul remain entirely ...

Importing vs Referencing Videos in Next.js - What is the Best Practice for Video Integration in Next.js?

I'm looking to use a video as a background in my banner design. Typically, with images in Next.js, I would import them and then pass the import as src (for example: import img from '@images/about-us-page/img.svg'). However, when attempting ...

The Azure Web App is unable to load the .json file

I am experiencing an issue with my Azure Web App. The app is failing to load a .json file that is stored on the server. Everything runs smoothly until the app needs to retrieve data from this specific .json file. This action is triggered by clicking a butt ...

Troubleshooting: Bootstrap Modal in .NET MVC not appearing on screen

Below is the code that manages order quotes and includes an if statement. The objective is to display an error message using TempData and Bootstrap Modal if the product quantity in the order exceeds the stock quantity. However, despite TempData not being n ...

Building a div element within a React function

For an exercise, I need to create an input field and a button. The goal is to display the text from the input field in a div/span below when the button is clicked. If I change the text in the input field and click the button again, the displayed text shoul ...

Tips on adjusting the color of a link once it has been clicked?

Looking for a link with a specific style? a { color: #999; &:hover { color: #008da0; } &:visited { color: #999; } /* I added this to test if it's gonna fix it, but it didn't */ } Upon clicking the link, it turns blue and remains s ...

Encountering an issue when trying to generate a button in Angular

I am currently using JavaScript to dynamically create a button in Angular. While I have been successful in creating the button, I am encountering an error when attempting to change the classname. The error message I am receiving is: Property 'clas ...

Different approach for searching and modifying nested arrays within objects

Here is an example of the object I am working with: { userId: 111, notes: [ { name: 'Collection1', categories: [ { name: 'Category1', notes: [ {data: 'This is the first note& ...

Attempting to convert PHP tables into PDF format by utilizing jsPDF-auto-table to generate a beautifully structured PDF file containing the results of a PHP query with multiple records

I'm new to stackoverflow but I find myself visiting it regularly for helpful tips. I've taken some code from the simple.html file that comes with the jsPDF auto-table plugin. However, I'm having trouble making it work with data generated by ...

Resolve the ajax issue and retrieve TCPDF after the server post

I am encountering an issue when trying to generate a TCPDF after validating a form. If the validation fails, the PHP file returns an error message. However, if the validation is successful, I want to return the PDF. The problem is that when the PDF is retu ...

Creating a responsive layout in HTML/CSS where the div element expands to fill the entire vertical space of its parent

Looking for assistance in creating a webpage layout like the one shown in this fiddle... http://jsfiddle.net/jeljeljel/5BSva/ I need the vertical line on the left side navigation tab to extend all the way down to the footer at the bottom of the page. Th ...

The data-bs-theme attribute of an element does not take precedence over the global theme

UPDATE: I recently included a placeholder item in my carousel because the local database feed was not working, and now the theme is malfunctioning locally as well. Something seems off with the carousel items causing issues. END OF UPDATE I successfully ...

What could be causing my CSS parallax effect to not work as expected?

I have been attempting to implement the parallax image technique following the Keith Clark tutorial, but I am facing difficulties in getting it to work correctly. Utilizing the skeleton CSS framework, my goal is to recreate an existing website in order to ...

Response from the controller upon choosing a value from the selection dropdown

Scenario: In this scenario, there are two tables in consideration: Firm table : ID (string), Firm(string) Firms table: FirmID(string FK), Name(string) The goal is to select a value from the Firm table, pass it to the controller as Firm, and then execut ...

Arrangement of 'const' variables within React Stateless Components

Consider a scenario where I have a straightforward React stateless component: const myComponent = () => { const doStuff = () => { let number = 4; return doubleNumber(number); }; const doubleNumber = number => { ...