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

Error: FileReader is not defined in Node.js (Nest.js) environment

I am working on converting my image to base64 using a custom function. However, when I try to execute the code, I encounter an error message stating ReferenceError: FileReader is not defined. This error has left me puzzled and unsure of its cause. Below i ...

When deciding between utilizing a Javascript animation library and generating dynamically injected <style> tags in the header, consider the pros and cons of each

We are currently in the process of developing a sophisticated single-page application that allows users to create animations on various widgets. For example, a widget button can be animated from left to right with changes in opacity over a set duration. Ad ...

Exploring VueJs 2.0: Iterating through components and updating properties

Searching for the optimal method to handle looping components has been my current focus. Below is an example of my coding dilemma. What I am attempting to accomplish is having payments data in my main component loop into child components. <tr v-for="p ...

Click to switch CodeMirror's theme

http://jsbin.com/EzaKuXE/1/edit I've been attempting to switch the theme from default to cobalt and vice versa, toggling each time the button is clicked. However, I am facing an issue where it only switches to the new theme once and doesn't togg ...

Router failure resulted in an internal server error

When navigating to a page in my router, I make a REST API request to retrieve data from the server in the beforeEnter clause as shown below: beforeEnter: (to, form, next) => { getData().then( (response) => { ...

What is the correct way to set a function as the value for an object without using quotation marks?

I am facing a challenge of generating very large JavaScript files using Node.js. Each file contains a const variable that holds values tailored for the specific file, with these values only known at runtime. For example: 'use strict' const lib ...

The dropdown selection for redirecting to a URL is malfunctioning within a PHP while loop

<?php $sql = "select * from letter where societyn='" . $_SESSION['socityname'] ."' "; $result = mysql_query($sql); $i=1; while($row=mysql_fetch_array($result)){ ?> <?php $id = $row['id']; ...

Why does ng-bind fail to display values from rootScope that have been set by using ng-click?

I am trying to save a variable within $rootScope. When I have the following structure, everything works fine and the second div displays the value: <html ng-app> ... <body> <button ng-click="$rootScope.pr = !$rootScope.pr"></b ...

Differences between Next.js Image and regular img tag regarding image quality

I am currently using Next.js and have noticed that my images appear slightly blurry when utilizing Next/Image. Below is a snippet of my code: <img src={url} width={articleWidth} /> <Image className="text-center" src={url} ...

Updating Navigation Bar Font

I am a novice in the process of constructing my own navigation bar for my website, and I am encountering difficulties when trying to customize the font (color, font-family, etc). Currently, the links in my navigation bar (such as home, contact, store, etc ...

Running NPM module via Cordova

After developing an app using cordova, I encountered a challenge where I needed to incorporate a node module that lacked a client-side equivalent due to file write stream requirements. My solution involved utilizing Cordova hooks by implementing an app_run ...

What are the steps for implementing timezone-js?

I found a project on GitHub that claims to convert one timezone to another. I've been trying to get it to work without success. After downloading and extracting the files, I created an HTML file with the following code: <html xmlns="http://www.w3. ...

Error compiling: Cannot locate module '../../common/form' within 'src/components/time'

An attempt to import the file form.jsx into the file time.jsx resulted in an error: Error message: Module not found: Can't resolve '../../common/form' in 'src/components/time' //src //common //form.jsx //compon ...

Toggle between different socket.io servers for seamless connectivity

I'm looking for help with a situation where I need a socket.io client to connect to server A, disconnect, and then connect to server B. Any ideas on how I can achieve this? Thanks in advance! UPDATE: Attached below is the code snippet that's gi ...

Trigger modal following unsuccessful registration

I have a method in the controller for registering users. [HttpPost] public ActionResult Register(RegisterViewModel register) { if (this.IsCaptchaValid("Captcha is not valid")) { if (ModelState.IsValid) { ...

Alter the background image of a DIV based on the selected menu item

I am working on a project that involves a div element with the class "jumbotron" which currently has a background image applied to it. Additionally, I have a menu consisting of 6 items that I would like to interact with. My goal is to dynamically change ...

What methods can be employed to prevent a custom CSS from overriding my personal styles?

Issue I've created a website with unique styles that I really like. However, I want to enhance its functionality by incorporating a custom dialog box from the BootBox library. The problem is that the extensive style sheet that comes with BootBox com ...

Learn the steps to update PHP headers on a specific website using AJAX

contactfrm.php <?php // Server side validation $name = $_POST['name']; $surname = $_POST['surname']; $bsubject = $_POST['subject']; $email= $_POST['email']; $message= $_POST['message']; $to = " ...

Separating Angular controllers into their own files can help prevent errors like "undefined is not a

I am currently revamping some Angular code and my goal is to organize things by type, such as keeping controllers in a separate folder. Currently, I have two controllers and an app.js file. However, I am encountering an issue with the error message "undef ...

When encountering an "uncaught SyntaxError" in the $.parseJSON function, one may want to investigate

When using this jQuery function, I encounter an Uncaught SyntaxError: Unexpected token u error if the cookie $.cookie('chk_ar') is undefined. function checkBgNoise() { // checks background noise option state, // activates 'on' click i ...