开发者

jQuery: outer html() [duplicate]

开发者 https://www.devze.com 2023-02-28 01:49 出处:网络
This question already has answers here: Get selected element's outer HTML (30 answers) Closed 3 years ago.
This question already has answers here: Get selected element's outer HTML (30 answers) Closed 3 years ago.

imagine 开发者_运维问答what we have something like this:

<div id="xxx"><p>Hello World</p></div>

if we call .html function in this way:

$("#xxx").html();

we will get:

<p>Hello World</p>

But i need to get:

<div id="xxx"><p>Hello World</p></div>

So, what i need to do? I think to add another wrapper around #xxx, but this is not a good idea.


Just use standard DOM functionality:

$('#xxx')[0].outerHTML

Or a bit simpler with .prop():

$('#xxx').prop('outerHTML')

outerHTML is well supported - verify at Mozilla or caniuse.


Create a temporary element, then clone() and append():

$('<div>').append($('#xxx').clone()).html();


No siblings solution:

var x = $('#xxx').parent().html();
alert(x);

Universal solution:

// no cloning necessary    
var x = $('#xxx').wrapAll('<div>').parent().html(); 
alert(x);

Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/


If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:

var myID = "xxx";

var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";
0

精彩评论

暂无评论...
验证码 换一张
取 消