Skip to content

Instantly share code, notes, and snippets.

@bruth
Last active December 17, 2015 07:08
Show Gist options
  • Save bruth/5570047 to your computer and use it in GitHub Desktop.
Save bruth/5570047 to your computer and use it in GitHub Desktop.
DOM-to-string jQuery plugin
(function($) {
$.scrape = function(options) {
options = options || {};
var el, page = [], clone;
// start with doctype
page.push('<!doctype html>');
// build the html tag since this cannot be captured as a child
// node
page.push('<html');
$.each($('html')[0].attributes, function() {
page.push(' ' + this.name + '="' + this.value + '"');
});
page.push('>');
// ensure all user-entered values are set as hard attributes
$(':text').each(function() {
el = $(this);
el.attr('defaultValue', el.val());
});
$('textarea').each(function() {
el = $(this);
el.attr('innerText', el.val());
});
$('select').each(function() {
$('option', this).each(function() {
el = $(this);
if (el.attr('selected')) {
this.setAttribute('selected', '');
} else {
el.removeAttr('selected');
}
});
});
$(':checkbox, :radio').each(function() {
el = $(this);
if (el.attr('checked')) {
this.setAttribute('checked', '');
} else {
el.removeAttr('checked');
}
});
// clone the DOM tree
clone = $('html').clone();
// set the type of scripts to something not understandable to prevent execution
clone.find('script').attr('type', 'text/void-javascript');
// remove additional elements, if specified
if (options.exclude) {
clone.find(exclude).remove();
}
// make all clickable elements not do anything
clone.find('a,button,input[type=button],input[type=submit]').attr({
'onClick': 'return false'
});
return page.join('') + clone.html() + '</html>';
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment