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.
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
Thanks Paul. Definitely interesting to see how others are implementing this. Being able to do this.outerHTML = value is certainly much more elegant
What's wring with good old DOM manipulation?
jQuery.fn.outerHTML = function() {
return $(this)[0].outerHTML;
};
Answer: incompatible across browsers.
Thanks for this great code…
Thanks for the help this is very useful.
The clone function might come in handy as an alternative
http://docs.jquery.com/Manipulation/clone
@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.
I like your implementation. Nice Job.
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.
http://darlesson.com/jquery/outerhtml/
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
/Sten
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 < and ≶? Doesn't that cause problems?
Pingback: Get selected element’s outer HTML - Programmers Goodies
Pingback: Extract script tags from a HTML string | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes
Pingback: How to select html content including the selector element [closed] | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes
Pingback: Get selected element's outer HTML | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes