9

For example, if the match is <div class="class1">Hello world</div>, I need to return

<div class="class1">Hello world</div>

not just "Hello world".

Thanks!

jeffu
  • 4,897
  • 2
  • 19
  • 6

4 Answers4

19

There's no built-in function for getting the outerHTML, but you can use this:

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

Then in your selector:
$('.class1').outerHTML() will give you what you are looking for.

Source of function

ichiban
  • 6,162
  • 3
  • 27
  • 34
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
3

@Jose Basilio's answer is great. But Brian Grinstead found a problem in this function when using IFrames: http://www.briangrinstead.com/blog/jquery-outerhtml-snippet

Here I put together Jose's way for also setting the outerHTML with Brian's solution for IFrames:

jQuery.fn.outerHTML = function(s) {
    if (s) {
        return this.before(s).remove();
    } else {
        var doc = this[0] ? this[0].ownerDocument : document;
        return jQuery('<div>', doc).append(this.eq(0).clone()).html();
    }
}
Community
  • 1
  • 1
Mariano Desanze
  • 7,847
  • 7
  • 46
  • 67
3

Check out this outerHTML plugin.

Michael Haren
  • 105,752
  • 40
  • 168
  • 205
1

I used .andSelf() with success:

http://api.jquery.com/andSelf/

ElementalStorm
  • 809
  • 12
  • 31