0

I was trying to get the entire HTML of an element using jQuery. Of course, .html() grabs only the inner HTML, but I wanted to retrieve the wrapping HTML too.

Imagine the following HTML:

<div id="wrapper">
    <div id="container_a">
        <p>Container A</p>
    </div>
    <div id="container_b">
        <p>Container B</p>
    </div>
</div>

Now, If I would do $("#container_a").html() I'd get <p>Container A</p> clearly. However, I want to get the following:

<div id="container_a">
    <p>Container A</p>
</div>

How would I achieve this?

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Deltanic
  • 1,009
  • 4
  • 11
  • 17

6 Answers6

3

You can do this using prop:

$("#container_a").prop('outerHTML');

FIDDLE DEMO

palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • 2
    Nice to see there's a jQuery-ish way (albeit it really seems like a bit of overkill, tbh) ... now I'm going to have to sift through the source code to see if `prop()` is actually proxying ... – vzwick Jun 13 '13 at 11:14
  • @vzwick Any update on that so far? – Deltanic Jun 13 '13 at 14:41
  • @vzwick All it really does is "fix" some things (like trying to access the `class` property, it changes it to `className` internally), but ends up just returning `element[ name ]` – Ian Jun 13 '13 at 17:08
1

use outerHTML

$("#container_a")[0].outerHTML

using plain javascript

document.getElementById("container_a").outerHTML;
bipen
  • 36,319
  • 9
  • 49
  • 62
1

First use clone for temporary then get html

$('div').append($('#container_a').clone()).html();
som
  • 4,650
  • 2
  • 21
  • 36
1

This should work

<script>
    var a=document.getElementById("container_a").outerHTML;
    alert(a);
</script>

Instead of alert we may use variable a in any other way...

0

use outerHTML

$("#container_a")[0].outerHTML

Demo ---> http://jsfiddle.net/uBDHY/1/

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

you can use .outerHTML for this

$("#container_a")[0].outerHTML
PSR
  • 39,804
  • 41
  • 111
  • 151