我正在尝试用javascript动态创建一个html文档对象,并将其链接到页面上的一个按钮。但是,当我运行下面的代码时,我得到了以下错误:"TypeError: Document.body属性必须是HTMLElement的实例。“MDN Web文档声明:“在HTML文档中,document.createElement()方法创建由tagName指定的HTML元素。”那么为什么我会得到这个错误?如何动态创建html文档?
window.onload = function() {
var new_document = new Document();
var new_body = new_document.createElement("body");
new_document.body = new_body;
}
发布于 2019-06-24 08:19:35
这个问题已经得到了回答。How to create Document objects with JavaScript
查看MDN,了解https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createHTMLDocument是如何
new Document()构造函数不是这样使用的。如果您在浏览器中使用控制台,您可以找到出现此错误的原因...
let doc = new Document();
doc.body;
// < null
doc.doctype;
// < null
// doc.doctype is a read only property also.
doc.__proto__;
// < Document {…}
// ‘document’ is the document the browser already created.
document.doctype;
// < “<!doctype html>“
document.__proto__;
//HTMLDocument {constructor: ƒ, Symbol(Symbol.toStringTag): "HTMLDocument"}
let body1 = doc.createElement('body');
let body = document.createElement('body');
body1.__proto__;
// Element {…}
body.__proto__;
// < HTMLBodyElement {…}
doc.body = body1;
// < Type Error: Not of type HTMLElement
// Now use the body element created by 'document'.
doc.body = body;
// Uncaught DOMException: Failed to set the 'body' property on 'Document': No document element exists.
// The body needs an document element to become a child node of.
let html = document.createElement('html');
doc.appendChild(html);
doc.body = body;
// No errors
doc.body;
// <body></body>
正如我们所看到的,new Document()构造函数创建了一个带有文档原型的完全空白的文档。当你用它创建元素时,这些元素有一个元素的原型。
浏览器创建的名为Document的文档的原型为HTMLDocument,它创建的元素的原型为HTMLElement。这就是doc.body的设置者所要寻找的。
https://stackoverflow.com/questions/56725661
复制相似问题