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
  • 122,518
  • 33
  • 200
  • 204
Deltanic
  • 939
  • 4
  • 10
  • 16

6 Answers6

3

You can do this using prop:

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

FIDDLE DEMO

palaѕн
  • 68,816
  • 17
  • 108
  • 129
  • 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
  • 35,563
  • 9
  • 45
  • 62
1

First use clone for temporary then get html

$('div').append($('#container_a').clone()).html();
som
  • 4,614
  • 2
  • 19
  • 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/

Mohammad Adil
  • 44,013
  • 17
  • 87
  • 109
0

you can use .outerHTML for this

$("#container_a")[0].outerHTML
PSR
  • 38,073
  • 36
  • 106
  • 149