首页 > 解决方案 > 使用 Object.setPrototype() 修补同一文档中的混合 HTML 和 XML 元素

问题描述

假设我将一个元素从 an 移动XMLDocument到 an HTMLDocument

// create XML doc
const xmlDoc = document.implementation.createDocument(null, 'my-root');

// reference the XML element
const myRoot = xmlDoc.childNodes[0];

// move to this HTML doc
document.body.appendChild(myRoot);

myRoot instanceof Element;     // true
myRoot instanceof HTMLElement; // false

myRoot.setAttribute('style', '...'); // doesn't render styles

// try to patch it
Object.getPrototypeOf(myRoot); // Element
Object.setPrototypeOf(myRoot, HTMLUnknownElement.prototype);
Object.getPrototypeOf(myRoot); // HTMLUnknownElement

myRoot.style;                        // error, illegal invocation
myRoot.setAttribute('style', '...'); // still doesn't render styles

由于myRoot是一个Node,它参与了 DOM 树,可以查询等等。它还具有所有与属性相关的功能Element

但:

为什么style设置原型后访问会中断?为什么设置原型后样式不起作用?

标签: javascripthtmlxmlbrowserelement

解决方案


推荐阅读