Alex Rivera | Logout

Get selected element's outer HTML

Asked 2010-03-10T19:09:02.810
816

I'm trying to get the HTML of a selected object with jQuery. I am aware of the .html() function; the issue is that I need the HTML including the selected object (a table row in this case, where .html() only returns the cells inside the row).

I've searched around and found a few very ‘hackish’ type methods of cloning an object, adding it to a newly created div, etc, etc, but this seems really dirty. Is there any better way, or does the new version of jQuery (1.4.2) offer any kind of outerHtml functionality?

Edit
Report

2 Answers

91

Extend jQuery:

(function($) {
  $.fn.outerHTML = function() {
    return $(this).clone().wrap('<div></div>').parent().html();
  };
})(jQuery);

And use it like this: $("#myTableRow").outerHTML();

answered 2010-11-15T02:27:23.603
10

you can also just do it this way

document.getElementById(id).outerHTML

where id is the id of the element that you are looking for

answered 2011-11-18T17:46:55.200

Your Answer