首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我不能赋值给动态创建的html文档的正文?

为什么我不能赋值给动态创建的html文档的正文?
EN

Stack Overflow用户
提问于 2019-06-24 00:09:00
回答 1查看 168关注 0票数 0

我正在尝试用javascript动态创建一个html文档对象,并将其链接到页面上的一个按钮。但是,当我运行下面的代码时,我得到了以下错误:"TypeError: Document.body属性必须是HTMLElement的实例。“MDN Web文档声明:“在HTML文档中,document.createElement()方法创建由tagName指定的HTML元素。”那么为什么我会得到这个错误?如何动态创建html文档?

代码语言:javascript
复制
window.onload = function() {
    var new_document = new Document();
    var new_body = new_document.createElement("body");
    new_document.body = new_body;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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()构造函数不是这样使用的。如果您在浏览器中使用控制台,您可以找到出现此错误的原因...

代码语言:javascript
复制
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的设置者所要寻找的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56725661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档