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,439
  • 6
  • 36
  • 59
Kupe3
  • 371
  • 2
  • 5
  • 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,500
  • 6
  • 25
  • 39
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,140
  • 1
  • 19
  • 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
  • 65,616
  • 14
  • 114
  • 135
-3

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

Matteo B.
  • 3,906
  • 2
  • 29
  • 43