Using JavaScript to fetch HTML and apply CSS dynamically

Is there a way to retrieve all HTML within a div along with the corresponding CSS? A majority of the CSS is defined in classes within an external stylesheet.

document.getElementById("mydiv")

Currently, using the above code only fetches the HTML with inline CSS. Is there a method to render the page where the CSS is applied inline, even if it originates from external CSS files?

Answer №1

Why not consider implementing the following function, extracted from this particular response:

function getStyles(a) {
    var sheets = document.styleSheets, stylesObject = {};
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a.is(rules[r].selectorText)) {
                stylesObject = $.extend(stylesObject, css2json(rules[r].style), css2json(a.attr('style')));
            }
        }
    }
    return stylesObject;
}

function css2json(css) {
    var styleObj = {};
    if (!css) return styleObj;
    if (css instanceof CSSStyleDeclaration) {
        for (var i in css) {
            if ((css[i]).toLowerCase) {
                styleObj[(css[i]).toLowerCase()] = (css[css[i]]);
            }
        }
    } else if (typeof css == "string") {
        css = css.split("; ");
        for (var i in css) {
            var splitCss = css[i].split(": ");
            styleObj[splitCss[0].toLowerCase()] = (splitCss[1]);
        }
    }
    return styleObj;
}

Here's an example of how you can use it:

var elementStyles = getStyles($("#myDiv")); // Get all styles from $("#myDiv")
$("#elementToApplyStyle").css(elementStyles); // Apply those styles to another element.

Next, to access each element within the <div>:

// .find('*') selects every child element.
$('#myDiv').find('*').each(function() {
    // Perform actions on each element using `this`
    console.log(this);
});

Utilize both methods together to gather the necessary information.

Answer №2

To display a separate HTML document within a div, you can utilize an iframe element.

<iframe src="example.htm" height="250" width="350"></iframe>

Answer №3

Here is a potential solution sourced from MDN. For more details, refer to the article https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

Below is the code snippet:

  function acquireStyle(){
    var element = document.getElementById("elem-container");
    var cssProperty = window.getComputedStyle(element,null).getPropertyValue("height");
    document.getElementById("output").innerHTML = cssProperty;
   }
  acquireStyle();
 #elem-container{
   position: absolute;
   left:     100px;
   top:      200px;
   height:   100px;
 }
<div id="elem-container">dummy</div>
<div id="output"></div>  

This approach allows you to loop through all elements and properties. While it may not include every line of code you need, it serves as a solid starting point.

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

filter array based on property value

var arr = [ {'a':1,'b':2}, {'a':1,'b':3}, {'a':1,'b':0}, ] I am looking to retrieve an array where the value of property b is 2 ...

I am having trouble starting a server on localhost with the command npm run dev

Currently, I am in the process of developing a website using react.js and tailwindcss. However, when attempting to test my progress by running the "npm run dev" command, I discovered that it is not starting a server on localhost. I am unfamiliar with this ...

Tips for incorporating external AMD modules with Angular2 using WebPack

In my current project using Angular2, TypeScript, and WebPack, I am looking to incorporate the Esri ArcGIS JavaScript API. The API can be accessed from the following URL: By importing Map from 'esri/Map';, I aim to import the corresponding modul ...

JavaScript sorted arrays are an efficient way to keep data

In my dataset, I have an array of objects representing various products. Each product object includes a field called ratingReviews and another field called price, which can either be a string or an object. If the price is represented as an object, it conta ...

Table with Typewriter Style CSS Animation

I came across an interesting typewriter effect implementation using CSS in an article on CSS Tricks I decided to play around with it and see if I could apply it to a hero image, which I found an example of on Codepen However, I noticed that the blinking ...

Vue js homepage footer design

I am struggling to add a footer to my Vue.js project homepage. Being an inexperienced beginner in Vue, I am finding it difficult to make it work. Here is where I need to add the footer Below is my footer component: <template> <footer> </ ...

Encountering an issue with the SSR module evaluation despite having SSR disabled in Svelte Kit

I needed a specific route in my app to not be server-side rendered. This can be achieved by setting export const ssr = false in the module script or configuring ssr: false in the svelte.config.js, as outlined in the Svelte documentation. Despite disabling ...

Several different factors

I need to develop a form that allows users to edit existing comments. The form will display a textarea containing the old comment text and a submit button. My goal is to send the newComment data via ajax to another script. However, I am facing an issue w ...

How to iterate through two arrays using AngularJS ng-repeat

I have been attempting to create a specific layout by iterating through two arrays However, the output I am receiving from the ng-repeats does not match my desired view Below is the current code that I am working with: $scope.properties = ["First name", ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

Guide to Inputting Numbers in a Form Field using a Pop-up Keypad (with Javascript/AJAX)

I am working on a small project that involves creating a keypad with buttons for all the digits, backspace, and decimal. When these buttons are clicked, they should populate a form field like a text box. The keypad will be located next to the form field as ...

Using JavaScript to Apply CSS Styles in JSF?

Is it possible to dynamically apply a CSS style to a JSF component or div using Javascript? I have been searching without any success. Below is some pseudo code: <div style="myJSStyleFunction("#{myBean.value}")"> stuff </div> The function wo ...

Tips for overlaying text onto a MaterialUI icon

https://i.stack.imgur.com/cFr5Y.pngI am currently working on a project that requires me to overlay a number on top of an icon. Specifically, I am utilizing the MaterialUI ModeComment icon and attempting to display text over it. Despite trying the following ...

In the console, a JSON string is displayed, however the PHP variable outputs as null

Below is the snippet of javascript code I am working with: $('.showEditForm').click(function () { var webpagefileID = this.id; if($('#editForm').css('display', 'none')) { $('#editForm').css ...

jQuery Ajax allows scripts to be contained within a page, even if the page itself is empty

Utilizing jQuery ajax to display an HTML page that includes javascript functions, here is my code: function ChartBook() { $.ajax({ url: '/Charts/ChartBook', dataType: 'html', id: 1, ...

React error message: "Cannot update state on a component that is not mounted" unless using the useEffect hook

(I am a beginner using Next.js + Styled Components and need help :)) I'm currently working on creating a "Netflix" style page, with unique catalog components. Each content item in the grid is a complex component named ContentItem.js that is repeated ...

Utilizing AJAX response to update the current URL in a Spring MVC application - A step-by-step guide

In my ongoing project using Spring MVC, the homepage features two input fields of String type. However, the regNo field accepts numbers as input. If a user enters a regNo, it should be directed to a specific method in the controller. On the other hand, if ...

What is the best method to customize CSS in ExtJS 5.0 by overriding a function?

Is there a way to dynamically add a rule to existing CSS using code, particularly in overrides? For example: var sheets = document.styleSheets; // Some code omitted for simplicity var sheet = sheets[sheets.length - 1]; sheet.insertRule('.overlay {flo ...

Add numerous submit buttons within a form. Upon clicking on a button, the form should be submitted to a specific URL using AJAX

I have a form with two submit buttons: one labeled as "SUBMIT" and the other as "SCHEDULE NEXT ROUND". When a user clicks on the "SUBMIT" button, the form values should be stored in the database and redirect to the view page. If they click on the "SCHEDULE ...

PHP isn't getting the AJAX POST data from the JavaScript file

I've been stuck on this issue for hours now, unable to find a solution. Here is the javascript code snippet: function sendMovement(cel) { var name = "test"; $.ajax({ type: 'POST', url: '../game.php', ...