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

4
  • This might help you... stackoverflow.com/questions/324486/… Commented Feb 13, 2020 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? Commented Feb 13, 2020 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 <style>tag ... Commented Feb 13, 2020 at 22:24
  • @G-Cyr, That sounds like a better option Commented Feb 14, 2020 at 15:11

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.