Yelotofu

Yelotofu ~ “In building standards compliant sites we are creating a better Web for the future.”

jQuery: outerHTML

Tags: , , , ,

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.

Similar Posts

4 Comments

  1. By Paul Bakaus at

    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. By 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. By Tonci at

    What’s wring with good old DOM manipulation?

    jQuery.fn.outerHTML = function() {
    return $(this)[0].outerHTML;
    };

  4. By caphun at

    Answer: incompatible across browsers.

Leave a Reply

* marks a required field.



(this will not be published)