简体   繁体   English

如何获取与当前DOM树相对应的HTML?

[英]How do I get HTML corresponding to current DOM tree?

jQuery("html").html() seems to retrieves most of it, except for the wrapping tag. jQuery(“ html”)。html()似乎会检索其中的大多数内容,包装标签除外。

DOM is heavily modified, so original source is of not that much use. DOM进行了大量修改,因此原始源没什么用。

  • Is it reliable? 它可靠吗?
  • Is it a good idea to just take jQuery's output and wrap ... around it? 仅接受jQuery的输出并包装...围绕它是一​​个好主意吗? I can see at least some doctype problems here, and inclusion of scripts which shouldn't be rerun. 我至少可以在这里看到一些doctype问题,并包含不应重新运行的脚本。
  • Any better way? 还有更好的方法吗?

EDIT: jQuery("").append(jQuery("html").clone()).html() almost works, except for doctype. 编辑:jQuery(“”)。append(jQuery(“ html”)。clone())。html()几乎可以工作,除了doctype。 Is there an easy way to get it? 有一种简单的方法可以得到它吗?

EDIT 2: I need the doctype mostly to get proper quirk/almoststandards/standards mode. 编辑2:我主要需要doctype以获得适当的怪癖/几乎标准/标准模式。 document.compatMode has half of it, is it enough? document.compatMode有一半,够了吗?

jQuery uses innerHTML to get the HTML. jQuery使用innerHTML来获取HTML。 You're not going to get the exact DOM state using this attribute. 您不会使用此属性获得确切的DOM状态。 For example the content of input values or the state of a select box will not stay the same unless you properly modify it before calling innerHTML . 例如, input值的内容或select框的状态将保持不变,除非您在调用innerHTML之前正确地对其进行了修改。

What is this wrapping tag you're talking about? 您在说什么wrapping标签? For most of it, innerHTML should work fine. 对于大多数情况,innerHTML应该可以正常工作。

For example, I use this code for the state of select and input boxes. 例如,我将此代码用于select框和input框的状态。

// it's defaultValue so we can use innerHTML
$("#divContentInside input").each(function () {
    this.defaultValue = this.value;
});
// go through each select and replace
// it's selection so we can use innerHTML
$("#divContentInside select > option").each(function () {
    if (this.selected) {
        this.setAttribute("selected", true);
    } else {
        this.removeAttribute("selected");
    }
});

I haven't found issues with state consistency of other elements, but there probably is. 我还没有发现其他元素的状态一致性问题,但是可能存在。

You can use standard DOM commands: 您可以使用标准的DOM命令:

To get the innerHTML of the HTML tag 获取HTML标签的innerHTML

document.body.parentNode.innerHTML

To get the Doctype information 获取文档类型信息

document.body.parentNode.previousSibling;

http://brandonaaron.net/blog/2007/06/17/jquery-snippets-outerhtml/ outerHTML implementation for jquery. http://brandonaaron.net/blog/2007/06/17/jquery-snippets-outerhtml/ jquery的externalHTML实现。

Edit 编辑

Doing a quick search came in the document.doctype option, here is a full reference to it. 在document.doctype选项中进行了快速搜索, 此处是对其的完整引用 Removed the old and now unnecessary text/code. 删除了旧的和现在不必要的文本/代码。

您是否尝试过$(document).html()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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