Use jQuery.prop("outerHTML") to get the HTML code of the HTML element including itself

JQuery.html() is to get the html code under the current node, and does not include the code of the current node itself, but we do need it sometimes, and it can be set by jQuery.prop("outerHTML").

Many jQuery users are deeply confused about this issue. Why can't you directly set the outerHTML of the html element in the various convenient methods of obtaining and setting attributes like in the DOM?

Because there is a built-in attribute outerHTML in the native JS DOM (see the case clearly, JS is case sensitive) to get the html code of the current node (including the current node), so you can get it with jQuery's prop()

One, jquery to get outerhtml

<div class="test"><p>hello,你好!</p></div>
<script>
$(".test").prop("outerHTML") //"<div class="test"><p>hello,你好!</p></div>"
$(".test").html() // "<p>hello,你好!</p>"
</script>

Two, jquery set outerhtml

 // "<div class="test"><p>hello,你好!</p></div>"替换成 "how are you!"
 $('.test').prop('outerHTML', 'how are you!');

Guess you like

Origin blog.csdn.net/weixin_42549581/article/details/109097945