简体   繁体   中英

jQuery removes wrapping element

I am loading a html file with jquery $.get and wrap the response. But jQuery removes my wrapper .

I made the following example which demonstrates my problem: https://jsfiddle.net/pwm76bp6/

Everyone who dont want to open the link here is the example code:

alert($('<div><div>Hallo</div></div>').html());

I would expect that the whole string should be alerted. Whats the problem here?

您需要阅读outerHTML属性。

 console.log($('<div><div>Hallo</div></div>').prop('outerHTML')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

用一个元素动态包装它,然后获取被包装元素的html()。

alert($('<div><div>Hallo</div></div>').wrap("<div></div>").parent().html());

It doesn't remove your wrapper. jQuery html() does return the contents of an element.

When you do $('<div>my content</div>') you creating an element, then you get the inner html with html() which is then alerted in your example.

With your code you will get the html of your outer element <div> . And the content of the outer <div> is <div>Hallo</div> .

You can do what you want with a default property:

alert($('<div><div>Hallo</div></div>')[0].outerHTML);

the function "html" does return the html content of a given element. In your case "html()" returns the content of the outer div, which excludes the outer itself.

You may can overcome this by wrapping your html like:

var html = '<div><div>Hallo</div></div>';
var outerHtml = $(html).wrap('<div />').parent().html();

hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM