当创建一个 div 时,它是 HTMLDivElement
的一个实例:
var d = document.createElement('div');
d instanceof HTMLDivElement; // true
d instanceof Element; // true
获取外部文档和窗口也是如此:
var frame = document.createElement('iframe');
document.body.appendChild(frame);
var doc2 = frame.contentWindow.document;
var d2 = doc2.createElement('div');
d2 instanceof frame.contentWindow.HTMLDivElement; // true
d2 instanceof Element; // false, different realm/dom
我已经尝试使用 Document
构造函数创建一个文档来处理外部 HTML 文档:
var doc = new Document();
var d = doc.createElement('div');
d instanceof Element; // true
因此,它创建了 Elements,并且这些元素与我们所在的领域处于同一领域。然而令我惊讶的是,它不键入其元素:
d instanceof HTMLDivElement; // false
d.constructor.name; // "Element"
为什么会这样,为什么当前文档创建类型化元素,而新文档只创建 Element
?
最佳答案
Document
构造函数不是特定于 HTML(因为有 XML 文档),您需要构造一个 HTMLDocument
,但它的构造函数是不可调用的。
如评论所述,创建文档的正确方法是通过 DOMImplementation#createHTMLDocument方法。
var doc = document.implementation.createHTMLDocument();
var d = doc.createElement('div');
d instanceof Element; // true;
d instanceof HTMLDivElement; // true
d.constructor.name; // "HTMLDivElement"
据我所知,通用文档(为 HTML 和 XML 共享)在某个时候分离为两个不同的构造函数。同时,他们使新的构造函数不可调用,并添加了 .createDocument()
(对于 XML)和 .createHTMLDocument()
(对于 HTML)方法。
关于javascript - 为什么在 `new Document` 下创建的元素包含错误的原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55812500/