Search code examples
javascripthtmlcssangularfroala

How to sniff css on div from existing website to add inline css to that div?


I would like to sniff the CSS that is currently applied to a certain div on my website, in order to insert inline style to that div (think of it like inlining before sending an email, even though it is before inserting into Word).

I'm well aware of inliner tools that inline the style for the whole webpage, and that I could send the whole webpage to tools like that (https://github.com/peterbe/premailer for instance), but I would like to avoid sending the whole page and grabbing the div afterward, if possible because it seems quite barbaric.

Any idea on how to grab the style currently applied to an element? I'm open to pre- and post-rendering.

If relevant, it's a div inside a FROALA editor, but useClass is a no-go, many styles are not set in classes but rather directly in dom tag styles:

a {
    color: ponytail's rainbow;
}

Solution

  • window.getComputedStyle(element[, pseudoElt]);
    

    The window.getComputedStyle() method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object or by simply indexing with CSS property names.

    Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

    Combining that with

    var computedStyle = window.getComputedStyle(element, null);
    
    for (prop in elementStyle) {
      if (elementStyle.hasOwnProperty(prop)) {
        out += "  " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
      }
    }
    

    does the trick