2

I want to get the whole HTML tag of an image (<img src="url" ... />). I can do it with .html() function if I refer to its parent:

<div id="image">
  <img src="url" />
</div>

and with JQuery:

$('#image').html()

But how could I do it if I don't have an image "only" parent:

<div id="image">
  <img src="url" />
  <!-- Here some stuff. E.g. -->
  <div><p>Something</p></div>
</div>

If I do $('#image').html() here, I'll get the whole content. If I do $('#image img').html() I'll get an empty string.

How could I get the whole <img> tag here?

Manolo
  • 24,020
  • 20
  • 85
  • 130

2 Answers2

4

You can use .outerHTML

$('#image img').prop('outerHTML')
$('#image img')[0].outerHTML //in this case you need to test whether $('#image img')[0] exists

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
4

In Javascript, it's as simple as:

document.getElementById('image').getElementsByTagName('img')[0].outerHTML

and as cookie monster says,

A nice alternative if IE6/7 support isn't needed would be document.querySelector("#image > img").outerHMTL

DEMO

Cilan
  • 13,101
  • 3
  • 34
  • 51