9
<div>
  <a href="#" class="selected">link1</a>  
  <a href="#">link1</a>
</div>

and using following

$('.selected').html() I get

link1

as a return value.

How can I get full html code of the selected DOM element, in this example to get

<a href="#" class="selected">link1</a>

instead?

thanks

Muhammad Usman
  • 12,212
  • 6
  • 35
  • 58
Kupe3
  • 359
  • 2
  • 4
  • 12

5 Answers5

19

jQuery object:

$('.selected')

become to DOM object:

$('.selected')[0]

UPDATE:

var str = $("<div />").append($('.selected').clone()).html();
console.log(str);
akai
  • 529
  • 2
  • 5
18

I know that this works on Chrome, don't know about the rest:

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

That property is from javascript (not jQuery) and gives you what you're looking for.

Deleteman
  • 8,210
  • 6
  • 24
  • 38
5

I made a solution similar to above, but with no cloning.

var test = $('#test').wrap('<div class="wrap-unwrap"></div>');
var str = test.parent().html();
test.unwrap();
console.log(str);
plong0
  • 2,122
  • 1
  • 18
  • 18
0

Simply using the outerHTML property may not work across all browsers. You will need to serialize it yourself for browsers without support for outerHTML. See this post for an explanation: How do I do OuterHTML in firefox?

Community
  • 1
  • 1
techfoobar
  • 63,712
  • 13
  • 108
  • 129
-3

You could try this jQuery plugin: http://darlesson.com/jquery/outerhtml/

Matmarbon
  • 3,739
  • 2
  • 28
  • 42