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...

$('#myTag').outerHTML();

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.

9 Comments

  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

    http://docs.jquery.com/Manipulation/clone

  8. caphun at

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

    http://docs.jquery.com/Manipulation/replaceWith

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

  9. Lepe at

    I like your implementation. Nice Job.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>