Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

HtmlCssInternet ExplorerFirebugGoogle Chrome-Devtools

Html Problem Overview


Like most web developers, I occasionally like to look at the source of websites to see how their markup is built. Tools like Firebug and Chrome Developer Tools make it easy to inspect the code, but if I want to copy a specific section and play around with it locally, it would be a pain to copy all the individual elements and their associated CSS. And probably just as much work to save the entire source and cut out the unrelated code.

It would be great if I could right-click a Element in Firebug and have a "Save HTML+CSS+JS for this Element" option. Does such a tool exist? Is it possible to extend Firebug or Chrome Developer Tools to add this feature?

Html Solutions


Solution 1 - Html

SnappySnippet

I finally found some time to create this tool. You can install SnappySnippet from Github. It allows easy HTML+CSS extraction from the specified (last inspected) DOM node. Additionally, you can send your code straight to CodePen or JSFiddle. Enjoy!

SnappySnippet Chrome extension

Other features

  • cleans up HTML (removing unnecessary attributes, fixing indentation)
  • optimizes CSS to make it readable
  • fully configurable (all filters can be turned off)
  • works with ::before and ::after pseudo-elements
  • nice UI thanks to Bootstrap & Flat-UI projects

Code

SnappySnippet is open source, and you can find the code on GitHub.

Implementation

Since I've learned quite a lot while making this, I've decided to share some of the problems I've experienced and my solutions to them, maybe someone will find it interesting.

First attempt - getMatchedCSSRules()

At first I've tried retrieving the original CSS rules (coming from CSS files on the website). Quite amazingly, this is very simple thanks to window.getMatchedCSSRules(), however, it didn't work out well. The problem was that we were taking only a part of the HTML and CSS selectors that were matching in the context of the whole document, which were not matching anymore in the context of an HTML snippet. Since parsing and modifying selectors didn't seem like a good idea, I gave up on this attempt.

Second attempt - getComputedStyle()

Then, I've started from something that @CollectiveCognition suggested - getComputedStyle(). However, I really wanted to separate CSS form HTML instead of inlining all styles.

Problem 1 - separating CSS from HTML

The solution here wasn't very beautiful but quite straightforward. I've assigned IDs to all nodes in the selected subtree and used that ID to create appropriate CSS rules.

Problem 2 - removing properties with default values

Assigning IDs to the nodes worked out nicely, however I found out that each of my CSS rules has ~300 properties making the whole CSS unreadable.
Turns out that getComputedStyle() returns all possible CSS properties and values calculated for the given element. Some of them where empty, some had browser default values. To remove default values I had to get them from the browser first (and each tag has different default values). The solution was to compare the styles of the element coming from the website with the same element inserted into an empty <iframe>. The logic here was that there are no style sheets in an empty <iframe>, so each element I've appended there had only default browser styles. This way I was able to get rid of most of the properties that were insignificant.

Problem 3 - keeping only shorthand properties

Next thing I have spotted was that properties having shorthand equivalent were unnecessarily printed out (e.g. there was border: solid black 1px and then border-color: black;, border-width: 1px itd.).
To solve this I've simply created a list of properties that have shorthand equivalents and filtered them out from the results.

Problem 4 - removing prefixed properties

The number of properties in each rule was significantly lower after the previous operation, but I've found that I sill had a lot of -webkit- prefixed properties that I've never hear of (-webkit-app-region? -webkit-text-emphasis-position?).
I was wondering if I should keep any of these properties because some of them seemed useful (-webkit-transform-origin, -webkit-perspective-origin etc.). I haven't figured out how to verify this, though, and since I knew that most of the time these properties are just garbage, I decided to remove them all.

Problem 5 - combining same CSS rules

The next problem I have spotted was that the same CSS rules are repeated over and over (e.g. for each <li> with the exact same styles there was the same rule in the CSS output created).
This was just a matter of comparing rules with each other and combining these that had exactly the same set of properties and values. As a result, instead of #LI_1{...}, #LI_2{...} I got #LI_1, #LI_2 {...}.

Problem 6 - cleaning up and fixing indentation of HTML

Since I was happy with the result, I moved to HTML. It looked like a mess, mostly because the outerHTML property keeps it formatted exactly as it was returned from the server.
The only thing HTML code taken from outerHTML needed was a simple code reformatting. Since it's something available in every IDE, I was sure that there is a JavaScript library that does exactly that. And it turns out that I was right (jquery-clean). What's more, I've got unnecessary attributes removal extra (style, data-ng-repeat etc.).

Problem 7 - filters breaking CSS

Since there is a chance that in some circumstances filters mentioned above may break CSS in the snippet, I've made all of them optional. You can disable them from the Settings menu.

Solution 2 - Html

I originally asked this question I was looking for a Chrome (or FireFox) solution, but I stumbled across this feature in Internet Explorer developer tools. Pretty much what I'm looking for (except for the javascript)

Element Source with Style

Result:

Element Source with Style result

Solution 3 - Html

Webkit browsers (not sure about FireBug) allow you to copy the HTML of an element easily, so that's one part of the process out of the way.

Running this (in the javascript console) prior to copying the HTML for an element will move all the computed styles for the parent element given, as well as all child elements, into the inline style attribute which will then be available as part of the HTML.

var el = document.querySelector("#someid");
var els = el.getElementsByTagName("*");

for(var i = -1, l = els.length; ++i < l;){
	
	els[i].setAttribute("style", window.getComputedStyle(els[i]).cssText);

}

It's a total hack and you'll have alot of "junk" css attributes to wade through, but should at least get your started.

Solution 4 - Html

I've created this tool years ago for the same purpose:
http://www.betterprogramming.com/htmlclipper.html

You're welcome to use and improve upon it.

Solution 5 - Html

This can be done by Firebug Plugin called scrapbook

You can check Javascript option in setting

enter image description here

Edit:

This can also help

> Firequark is an extension to Firebug > to aid the process of HTML Screen > Scraping. Firequark automatically > extracts css selector for a single or > multiple html node(s) from a web page > using Firebug (a web development > plugin for Firefox). The css selector > generated can be given as an input to > html screen scrapers like Scrapi to > extract information. Firequark is > built to unleash the power of css > selector for use of html screen > scraping.

Solution 6 - Html

divclip is an updated version of Florentin Sardan's htmlclipper

with modern enhancements: ES5, HTML5, scoped CSS...

you can programmatically extract a stylized div with:

var html = require("divclip").bySel(".article-body");
console.log(html);

Enjoy.

Solution 7 - Html

There is no plugins needed. It can be done very simply with Internet Explorer 11 native Developer Tools with just one click, very clean. Just right on an element and inspect that element, and right click on some block and choose "Copy element with styles". You can see it in the below image.

It provides the css code very clean, like

.menu { 
    margin: 0;
}
.menu li {
    list-style: none;
}

Solution 8 - Html

Lately I created a chrome extension "eXtract Snippet" for copying the inspected element, html and only the relevant css and media queries from a page. Note that this would give you the actual relevant CSS

https://chrome.google.com/webstore/detail/extract-snippet/bfcjfegkgdoomgmofhcidoiampnpbdao?hl=en

Solution 9 - Html

A tool with a single solution for this I'm unaware of, but you can use Firebug and Web Developer extension at the same time.

Use Firebug to copy the html section you need (Inspect Element) and Web Developer to see which css is associated with an element (Calling Web Developer "View Style Information" - it works like Firebug's "Inspect Element", but instead of showing the html markup it shows the associated CSS with that markup).

It's not exactly what you want (one click for everything), but it's pretty close, and at least intuitive.

'View Style Information' result from Web Developer Extension

Solution 10 - Html

I also need this feature on Firebug! Until then, another approach is to use this online service to remove classes and convert the css to inline styles.

Solution 11 - Html

http://clipboardjs.com does this and quite well. Although your expectation of the copied version being exactly as in the original so you can play and learn with it, may not be realistic.

Solution 12 - Html

Just copy the part you want from the webpage and paste it in the wysiwyg editor. Check the html source by clicking on the "source" button on the editor toolbar.

I've found this most easiest way when I was working on a Drupal site. I use wysiwyg CKeditor.

Solution 13 - Html

jQuery.fn.extend({
getStyles: function() {
    var rulesUsed = [];
    var sheets = document.styleSheets;
    for (var c = 0; c < sheets.length; c++) {
        var rules = sheets[c].rules || sheets[c].cssRules;
        for (var r = 0; r < rules.length; r++) {
            var selectorText = rules[r].selectorText.toLowerCase().replace(":hover","");
            if (this.is(selectorText) || this.find(selectorText).length > 0) {
                rulesUsed.push(rules[r]);
            }
        }
    }
    var style = rulesUsed.map(function(cssRule) {
        return cssRule.selectorText.toLowerCase() + ' { ' + cssRule.style.cssText.toLowerCase() + ' }';
    }).join("\n");
    return style;
}
});

> usage:$("#login_wrapper").getStyles()

Solution 14 - Html

There is a firefox plugin that saves the whole page's HTML, CSS, etc.. but I have not seen one that does a partial save.

I remember IE 5.5 had what you were looking for though ;)

Solution 15 - Html

I've adapted the top voted answer as a dragabble bookmarklet.

Just visit this page and drag the "Run jQuery Code" button to your bookmark bar.

Solution 16 - Html

I gone through all the tools mentioned as answer here. But they give repeated, dirty HTML CSS with beautiful face you were staring up on. They don't give you JS.

What I do:

  1. First I filter ads which are not require on the page
  2. Then , save complete webpage along with linking resources.
  3. Remove unnecessary HTML, CSS and JS
  4. keep unlinking resources one-by-one carefully.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkenwarnerView Question on Stackoverflow
Solution 1 - HtmlKonrad DzwinelView Answer on Stackoverflow
Solution 2 - HtmlkenwarnerView Answer on Stackoverflow
Solution 3 - HtmlCollective CognitionView Answer on Stackoverflow
Solution 4 - HtmlFlorentinView Answer on Stackoverflow
Solution 5 - HtmlJitendra VyasView Answer on Stackoverflow
Solution 6 - Htmlato3787045View Answer on Stackoverflow
Solution 7 - HtmlGarryOneView Answer on Stackoverflow
Solution 8 - Htmlmelwyn pawarView Answer on Stackoverflow
Solution 9 - HtmlGmonCView Answer on Stackoverflow
Solution 10 - HtmlAcyraView Answer on Stackoverflow
Solution 11 - HtmlMoin ZamanView Answer on Stackoverflow
Solution 12 - HtmlKevin SijiView Answer on Stackoverflow
Solution 13 - Htmlgeekbytes0xffView Answer on Stackoverflow
Solution 14 - HtmlChris AbramsView Answer on Stackoverflow
Solution 15 - Htmlripper234View Answer on Stackoverflow
Solution 16 - HtmlAmit Kumar GuptaView Answer on Stackoverflow