2

I am trying to get the HTML page's source code using JavaScript (kind of like screenshot). And for styling, I am using external CSS. However, when I get the HTML source code, the styling won't be applied because I won't be able to get the CSS properties for the elements.

So, I am wondering if I can replace the CSS class name with actual CSS properties defined in that class. e.g.

for the HTML element,

<div class="exampleClass"><div>

And CSS,

.exampleClass {
    background-color:#FFFFFF;
}

Then the extracted source code using Javascript will be

<div style="background-color:#FFFFFF;"><div>

How can I do this thing in JavaScript? Thanks

Rahul Vala
  • 695
  • 8
  • 17
  • This might help you... https://stackoverflow.com/questions/324486/how-do-you-read-css-rule-values-with-javascript – Dawid Zbiński Feb 13 '20 at 20:37
  • Maybe its possible to hack something but to get the full "cascading" nature of css this would be fairly tricky. Why don't you just pull down the stylesheets too? – James Feb 13 '20 at 20:39
  • 1
    you will still be missing: pseudo classes, `@media`, `@print`,, `@import`, `@keyframes` , .... , you 'd better import the whole style sheet and store it in ` – G-Cyrillus Feb 13 '20 at 22:24
  • @G-Cyr, That sounds like a better option – Rahul Vala Feb 14 '20 at 15:11

2 Answers2

1
function getCSSPropertiesBySelector(selector) {
    return [...document.styleSheets].map(stylesheet => {
        var g = [...stylesheet.cssRules].find(rule => rule.selectorText === selector);
        if (g) {
            return g.style.cssText;
        }
    }).find(r => r);
}

Mostly based off of https://stackoverflow.com/a/16966533/1799147

getCSSPropertiesBySelector('.logo')
//"display: block; grid-area: I / I / I / I; width: 200px; height: 44px; margin-right: 24px;"

There's probably better ways to do this but it gets the job done. It won't work if there's a duplicate class in this example, you'd probably want it to be changed to append to the properties if you had the same class in another stylesheet

Jacob Morrison
  • 610
  • 2
  • 10
  • 19
0

You can assign the desired class to the tag HTML in javascript. For example:

const div = document.createElement('div');
div.className = 'exampleClass';
document.body.appendChild(div);

Or

div.classList.add('exampleClass');