jQuery获取正文中的html以及body标签

jQuery to get the html inside body along with body tag

本文关键字:以及 body 标签 html 获取 正文 jQuery      更新时间:2023-09-26

我知道如何在正文标签中抓取html,我可以通过以下方式做到这一点

$("body").html();

上面的行向我返回了 body 标签内的 html。但是我想要 html 倾斜正文标签。例如

<body attr1="abc" attr2="def" attr3="xyz">
    <div class="container">
         I am in trouble.Please HELP me!!
    </div>
</body>

想要一些东西,它向我返回 html 以及正文标签及其所有属性。我怎样才能做到这一点??

您可以使用

以下命令获取outerHTML

$('body')[0].outerHTML

演示

outrHTML - the thing you need here

MDN 定义 - 元素 DOM 接口的 outerHTML 属性获取描述元素(包括其后代(的序列化 HTML 片段。可以将其设置为将元素替换为从给定字符串解析的节点。

所以代码将是

$("body")[0].outerHTML

或纯JavaScript

document.body.outerHTML