get self HTML code with jQuery [duplicate]

2020-07-09 10:10发布

<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

标签: jquery
5条回答
女痞
2楼-- · 2020-07-09 10:41

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);
查看更多
趁早两清
3楼-- · 2020-07-09 10:46

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

查看更多
老娘就宠你
4楼-- · 2020-07-09 10:49

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.

查看更多
在下西门庆
5楼-- · 2020-07-09 10:57

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?

查看更多
淡お忘
6楼-- · 2020-07-09 11:01

jQuery object:

$('.selected')

become to DOM object:

$('.selected')[0]

UPDATE:

var str = $("<div />").append($('.selected').clone()).html();
console.log(str);
查看更多
登录 后发表回答