Retrieve the computed style of a cloned element that has not yet been appended to the document

I am dealing with an HTML page that looks like this:

<div id="cloneDiv">
    <h1>
        <a href="">ASUS Vivotab Smart Black Office 2013 H&S ME400C-C2-BK 10.1-Inch 64GB Tablet
            (Black)</a>
    </h1>
    <div id="fordBackgroundImage" style="display: inline-block; background-position: center center; width: 1200px;
        height: 565px; background-image: url('http://www.ford.com/ngbs-services/resources/ford/edge/2013/npcolorizer/edg13_ingotsilver.jpg');
        background-repeat: no-repeat; background-attachment: scroll; position: relative;">
        <div style="position: absolute; color: white; font-weight: bold; top: 50px; left: 100px; font-size: 50px;">
            Try new ford jeep!
        </div>
    </div>
    <p>
        <img alt="" src="http://ecx.images-amazon.com/images/I/81UsKLK%2B6LL._SX342_.jpg"
            class="border thumb0 selected" style="cursor: pointer;">
    </p>
    <p>
        <img border="0" src="http://g-ecx.images-amazon.com/images/G/01/kindle/otter/dp/o1_slate_sm._V358729399_.jpg"
            style="width: 320px; height: 282px;">
    </p>
 </div>

I have a JavaScript function that converts elements to computed style elements:

function MakeCssInline(elementParam) {
var domE = $(elementParam).get()[0];
var cssText = window.getComputedStyle(domE).cssText;
$(elementParam).attr("style", cssText);
// children
var items = domE.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
    var domE2 = items[i];
    var cssText2 = window.getComputedStyle(domE2).cssText;
    $(items[i]).attr("style", cssText2);
}
 };

When I call this function on the original element, it works fine but changes the original element's HTML:

MakeCssInline($("#cloneDiv"));

However, when I try to call this function on a cloned element, it does not work:

var cloneElement = $("#cloneDiv").clone();
MakeCssInline(cloneElement);

The styles are not applied to the element because I did not append it to the body element. Since I don't want to interfere with the original element, is there a way to get the computed style of a cloned element using JavaScript?

Answer №1

After taking inspiration from Felix Kling's suggestion, I developed a simple function to create inline CSS for elements.

function ConvertToInlineCss(element) {
    var clonedElement = $(element).clone();
    $(clonedElement).find("script").remove();
    $(clonedElement).find("link").remove();
    $(clonedElement).find("iframe").remove();
    
    var originalDomElement = $(element).get()[0];
    var clonedDomElement = $(clonedElement).get()[0];
    
    var cssText = window.getComputedStyle(originalDomElement).cssText;
    $(clonedElement).attr("style", cssText);
    
    var childElementsOriginal = originalDomElement.getElementsByTagName("*");
    var childElementsCloned = clonedDomElement.getElementsByTagName("*");
    for (var i = 0; i < childElementsOriginal.length; i++) {
        var childDomElement = childElementsOriginal[i];
        var cssTextChild = window.getComputedStyle(childDomElement).cssText;
        $(childElementsCloned[i]).attr("style", cssTextChild);
    }
    
    return clonedDomElement;
};

Answer №2

Create a hidden element, append it to the body, extract the necessary information, and finally remove it from the DOM.

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

Exploring the concept of ng-model with undefined values in AngularJS

Having an input with a $watch function that updates a search query in real time through AngularJS, I am encountering an issue. Despite setting the initial value of the model to empty, it automatically triggers the search and displays results. My concern i ...

Utilizing Odometer to pass a variable to jQuery

I'm interested in incorporating a jQuery odometer into a master page to display dynamic information. I found a helpful resource for this at this link. To achieve this, I need to fetch data from a SQL Server database using C# and then pass it to the J ...

Setting the size of a box using CSS in HTML pages

I am facing issues with resizing boxes. Below is the code snippet: <!DOCTYPE html> <html lang="en"> <head> <style> .wrapper { text-align: center; } #bubble { display: inline; -moz ...

Cannot extract the 'name' property from 'e.target' because it is not defined

I encountered an error message stating that I cannot destructure the property 'name' of 'e.target' because it is undefined within the createform() method. Despite highlighting the line causing the error, I am still unable to comprehend ...

Develop a program in Python using Selenium to automate web scraping in a loop

I am looking to create a loop that will allow me to extract the individual time figures for each horse in all eight races from the at the races website. Here is an example of the first race (17:15) out of the eight: from selenium import webdriver from s ...

The ng-click event is not triggering the Controller Function as expected

This is the Code for My View <div ng-controller="signupCtrl"> <ul class="list-group" > <li class="list-group-item"> <div class="form-group"> <input type="text" ng-model="signupCtrl.firstName"> ...

When you reach the end of the page, the loadMore function is triggered multiple times

On my webpage, I have a list of profiles that are displayed. When the user reaches the bottom of the page, more data should be loaded through the loadMore function. While the loadMore function itself works correctly, I am facing an issue with the listener. ...

Triggering a sweet alert on a mouse click

Here is a code snippet I found on . It shows an alert box that doesn't disappear when clicked outside of it. swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, ...

What steps can I take to make sure that the content on my website is properly sized to fit within the browser window?

I'm currently working on a website project for my college assignment and I could really use some assistance with a significant issue that I've encountered. Whenever I open the html file of my website on my MacBook, which has a screen resolution ...

Using JavaScript and jQuery to toggle visibility of a dynamically created input field

This script dynamically generates a group of elements consisting of four input fields. Once an element is created, you can select or deselect it, which will trigger the corresponding editor to appear. I have implemented a function to specifically hide the ...

The request is unsuccessful due to the absence of the 'Access-Control-Allow-Origin' header

I've set up a form using Get Response (the email client) and I'm attempting to implement ajax in order to display a custom success or failure message upon submission. The code seems to be functioning correctly. However, as soon as I connect the a ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Displaying entries of input data

I have an application that includes a modal window with filters, but I am looking to add another type of filter. However, I am struggling with implementing it in React and would appreciate any help with the code or recommended links. Essentially, I want t ...

How can I trigger a page postback in ASP.NET after downloading a file?

Here is my current scenario: The user clicks on a LinkButton, triggering a PostBack on the page. However, I also need to initiate a file download for the user simultaneously. To achieve this, I added the following code to the LinkButton: lnkPrint.Attri ...

Sharing information between React components involves passing data as props. By sending data from

Brand new to React and still figuring things out. Here's the scenario: <div> <DropDown> </DropDown> <Panel> </Panel> </div> After selecting a value in the dropdown and storing it as currentL ...

Using AJAX to populate a dropdown menu in a CodeIgniter application

I'm having an issue with using AJAX to populate a dropdown option. Here is the JavaScript code I am using: <script type="text/javascript"> $(document).ready(function(){ $("#sepatu").click(function(e){ e.preventDefault() ...

Tips on obtaining a Firebase ID

Does anyone have a solution for retrieving the unique id from Firebase? I've attempted using name(), name, key, and key() without any success. Although I can view the data, I'm struggling to find a way to retrieve the id. This information is cru ...

Why is the outline buttons class only displaying gray colors for me?

I'm having trouble with the outline buttons class (btn btn-outline-primary) in Bootstrap. For some reason, all the buttons appear gray instead of colored as they should. Here's an example of how the buttons should look: https://ibb.co/ChKf83y, bu ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

Randomly swap images in HTML when a button is clicked

In order to change images randomly on mouse click, I came across this solution: <SCRIPT LANGUAGE="Javascript"> function banner() { } ; b = new banner() ; n = 0 b[n++]= "<A HREF='index.html'><IMG SRC='images/pic1.jpg'> ...