48

I often find nice stylings on the web. To copy the CSS of a DOM element, I inspect that element with Google Chrome Developer Tools, look at the various CSS properties, and copy those manually to my own stylesheets.

Is it possible to easily export all CSS properties of a given DOM element?

Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • 1
    Somebody could probably make a quick program to do this. – Freesnöw Oct 13 '11 at 12:56
  • 3
    Not a direct answer, but with Chrome Developer Tools, you can click inside Styles or Computed Styles, hit Ctrl+A and then Ctrl+C to copy all the styles in those given areas. It's not perfect in the Style tab because it picks up some extra stuff. Better than selecting them one by one I guess. – Doozer Blake Oct 13 '11 at 13:18
  • I could make a bookmarklet to do that... – zzzzBov Oct 13 '11 at 13:23
  • Must say I am quite surprised that no one has come up with something to do this although I suppose it is easy enough to copy and paste from your developer tool of choice. Saying that I think being able to export an elements css would be a nice feature. – Andy Rose Oct 13 '11 at 14:11
  • Firebug is also a better plugin that can be used to inspect html elements and copy the style. – James Jithin Oct 13 '11 at 15:01
  • Have you seen CSS Usage Addon in firefox – defau1t Oct 23 '11 at 14:18
  • Check out the Chrome extension that was posted on a similar question: http://stackoverflow.com/questions/7754469/export-css-of-dom-elements – Justin Ryder Feb 27 '15 at 15:37

3 Answers3

56

Here is the code for an exportStyles() method that should return a CSS string including all inline and external styles for a given element, except default values (which was the main difficulty).

For example: console.log(someElement.exportStyles());

Since you are using Chrome, I did not bother making it compatible with IE. Actually it just needs that the browsers supports the getComputedStyle(element) method.

Element.prototype.exportStyles = (function () {  

    // Mapping between tag names and css default values lookup tables. This allows to exclude default values in the result.
    var defaultStylesByTagName = {};

    // Styles inherited from style sheets will not be rendered for elements with these tag names
    var noStyleTags = {"BASE":true,"HEAD":true,"HTML":true,"META":true,"NOFRAME":true,"NOSCRIPT":true,"PARAM":true,"SCRIPT":true,"STYLE":true,"TITLE":true};

    // This list determines which css default values lookup tables are precomputed at load time
    // Lookup tables for other tag names will be automatically built at runtime if needed
    var tagNames = ["A","ABBR","ADDRESS","AREA","ARTICLE","ASIDE","AUDIO","B","BASE","BDI","BDO","BLOCKQUOTE","BODY","BR","BUTTON","CANVAS","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","COMMAND","DATALIST","DD","DEL","DETAILS","DFN","DIV","DL","DT","EM","EMBED","FIELDSET","FIGCAPTION","FIGURE","FONT","FOOTER","FORM","H1","H2","H3","H4","H5","H6","HEAD","HEADER","HGROUP","HR","HTML","I","IFRAME","IMG","INPUT","INS","KBD","KEYGEN","LABEL","LEGEND","LI","LINK","MAP","MARK","MATH","MENU","META","METER","NAV","NOBR","NOSCRIPT","OBJECT","OL","OPTION","OPTGROUP","OUTPUT","P","PARAM","PRE","PROGRESS","Q","RP","RT","RUBY","S","SAMP","SCRIPT","SECTION","SELECT","SMALL","SOURCE","SPAN","STRONG","STYLE","SUB","SUMMARY","SUP","SVG","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TIME","TITLE","TR","TRACK","U","UL","VAR","VIDEO","WBR"];

    // Precompute the lookup tables.
    for (var i = 0; i < tagNames.length; i++) {
        if(!noStyleTags[tagNames[i]]) {
            defaultStylesByTagName[tagNames[i]] = computeDefaultStyleByTagName(tagNames[i]);
        }
    }

    function computeDefaultStyleByTagName(tagName) {
        var defaultStyle = {};
        var element = document.body.appendChild(document.createElement(tagName));
        var computedStyle = getComputedStyle(element);
        for (var i = 0; i < computedStyle.length; i++) {
            defaultStyle[computedStyle[i]] = computedStyle[computedStyle[i]];
        }
        document.body.removeChild(element); 
        return defaultStyle;
    }

    function getDefaultStyleByTagName(tagName) {
        tagName = tagName.toUpperCase();
        if (!defaultStylesByTagName[tagName]) {
            defaultStylesByTagName[tagName] = computeDefaultStyleByTagName(tagName);
        }
        return defaultStylesByTagName[tagName];
    }

    return function exportStyles() {
        if (this.nodeType !== Node.ELEMENT_NODE) {
            throw new TypeError("The exportStyles method only works on elements, not on " + this.nodeType + " nodes.");
        }
        if (noStyleTags[this.tagName]) {
            throw new TypeError("The exportStyles method does not work on " + this.tagName + " elements.");
        }
        var styles = {};
        var computedStyle = getComputedStyle(this);
        var defaultStyle = getDefaultStyleByTagName(this.tagName);
        for (var i = 0; i < computedStyle.length; i++) {
            var cssPropName = computedStyle[i];
            if (computedStyle[cssPropName] !== defaultStyle[cssPropName]) {
                styles[cssPropName] = computedStyle[cssPropName];
            }
        }

        var a = ["{"];
        for(var i in styles) {
            a[a.length] = i + ": " + styles[i] + ";";
        }
        a[a.length] = "}"
        return a.join("\r\n");
    }

})();

This code is base on my answer for a slightly related question: Extract the current DOM and print it as a string, with styles intact

Community
  • 1
  • 1
Luc125
  • 5,752
  • 34
  • 35
  • 2
    Somehow I don't think you are including `:focus`, `:blur`, etc. Good job so far, though! – Randomblue Oct 13 '11 at 15:26
  • @Randomblue: That's true, it doesn't include pseudo-class styles. I'll think about it! – Luc125 Oct 13 '11 at 15:32
  • I've set a bounty for pseudo-classes! I hope you'll get it. – Randomblue Oct 17 '11 at 14:47
  • It is possible to find the styles associated with pseudo-elements like `:first-letter` or `:first-line` by using for example `getComputedStyle(element, ":first-letter")`, but implementing it in my code above could will in many cases triple the needed computation time, just for two pseudo-elements, and make it even slower for more pseudo-elements... – Luc125 Oct 23 '11 at 14:15
  • ... For pseudo-classes (`:active`, `:hover`, etc), `getComputedStyle` doesn't work at all. Anyway, what if the page contains a code like `theElement.addEventListener("onmouseover", function (event) { $(this).addClassName(someClass); });` ? The only way to retrieve the dynamic styles will then be either programmatically trigger the event - which might be ok for hover events, but *not* for click or focus events! - or manually hovering or focusing the element before calling `exportStyles`, which is not exactly what you wanted I'm sorry... – Luc125 Oct 23 '11 at 14:20
  • you can use something like this `document.querySelector('your-querry-selector').exportStyles().replace(/\r?\n|\r/g,'').replace('{','').replace('}','').split(";").forEach(function(item, index){var key, value, touple = item.split(":");key=touple[0];value=touple[1]; if(typeof window.temp === 'undefined'||index==0)window.temp=[];temp[key]=value;});` if you want to get key-value format. – sajed zarrinpour Aug 13 '19 at 12:25
2

I'm quoting Doozer Blake's excellent answer, provided above as a comment. If you like this answer, please upvote his original comment above:

Not a direct answer, but with Chrome Developer Tools, you can click inside Styles or Computed Styles, hit Ctrl+A and then Ctrl+C to copy all the styles in those given areas. It's not perfect in the Style tab because it picks up some extra stuff. Better than selecting them one by one I guess. – Doozer Blake 3 hours ago

You can do the same using Firebug for Firefox, by using Firebug's "Computed" side panel.

Community
  • 1
  • 1
Anirvan
  • 6,214
  • 5
  • 39
  • 53
1

There are a few ways to almost do this.

Have a look at FireDiff

Also have a look at cssUpdater This is for local CSS only]

And see this Q for more similar tools: Why can't I save CSS changes in Firebug?

Also this paid product claims to be able to do this: http://www.skybound.ca/

Community
  • 1
  • 1
Moin Zaman
  • 25,281
  • 6
  • 70
  • 74