Skip to content

Instantly share code, notes, and snippets.

@ScottPhillips
Created July 11, 2012 21:06
Show Gist options
  • Save ScottPhillips/3093538 to your computer and use it in GitHub Desktop.
Save ScottPhillips/3093538 to your computer and use it in GitHub Desktop.
jQuery OuterHTML plugin
jQuery.fn.extend( {
outerHtml: function( replacement ) {
// We just want to replace the entire node and contents with
// some new html value
if (replacement) {
return this.each(function (){ $(this).replaceWith(replacement); });
}
/*
* Now, clone the node, we want a duplicate so we don't remove
* the contents from the DOM. Then append the cloned node to
* an anonymous div.
* Once you have the anonymous div, you can get the innerHtml,
* which includes the original tag.
*/
var tmp_node = $("<div></div>").append( $(this).clone() );
var markup = tmp_node.html();
// Don't forget to clean up or we will leak memory.
tmp_node.remove();
return markup;
}
});
<div class="outer" >Fun Stuff</div>
// get the entire html for the <div class="outer" > tag
var x = $('.outer').outerHtml();
// replace all div tags with <div class="outer" >Fun Stuff</div>
$('div').outerHtml(x);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment