jQuery: outerHTML

The outerHTML property (IE only) could sometimes be very handy, especially if you’re trying to replace an element entirely. Brandon Aaron has very kindly given us a outerHTML plugin that does half the job as it doesn’t support replacements. The following code snippet fills in the blanks:

jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();

To get the outerHTML value of an element do this…


To replace #myTag entirely do this…

$('#myTag').outerHTML("<p>My brand new #myTag.</p>");

Hope this helps someone :)

Update: There’s now a demo page.


  1. Hey Ca Phun!

    Just wanted to let you know I found another implementation of outerHTML some days ago, while working with the SVG suff, and it also defines the setter, seems pretty robust (I used it).

    Look here: http://webfx.eae.net/dhtml/ieemu/htmlmodel.html

    Cheers :)

  2. caphun at

    Thanks Paul. Definitely interesting to see how others are implementing this. Being able to do this.outerHTML = value is certainly much more elegant :)

  3. Tonci at

    What's wring with good old DOM manipulation?

    jQuery.fn.outerHTML = function() {

    return $(this)[0].outerHTML;


  4. caphun at

    Answer: incompatible across browsers.

  5. Kevin Pirkl at

    Thanks for this great code…

  6. Parag Lohiya at

    Thanks for the help this is very useful.

  7. Drew at

    The clone function might come in handy as an alternative


  8. caphun at

    @drew: I think the replaceWith is a closer alternative:


    As I remember that wasn't around when I made this post.

  9. Lepe at

    I like your implementation. Nice Job.

  10. Dee at

    Just to add to the list, another jQuery outerHTML method that allows you to get or replace the element inheriting the replacing content to the chaining. A good option to replaceWith() method as well.


  11. Hi,

    Just want to give you credit for this simple but very handy piece of code :-) Thank you for sharing! I myself is working on something which will be a very nice feature for people in the jQuery world – watch my blog :-)


  12. Danny at

    Maybe this wasn't possible when you originally wrote this, or maybe it's slower, but here's what I do:

    jQuery.fn.outerHTML = function(s) {

    return (s) ? jq(this).replaceWith(s) : jq(this).clone().wrap('').parent().html();


    Seems much easier to read to me. Also, why do you use &lt; and &lg;? Doesn't that cause problems?

  13. Pingback: Get selected element’s outer HTML - Programmers Goodies

  14. Pingback: Extract script tags from a HTML string | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes

  15. Pingback: How to select html content including the selector element [closed] | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes

  16. Pingback: Get selected element's outer HTML | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes