首页 > 解决方案 > 从完整的 HTML 标记创建模板元素/文档片段

问题描述

似乎不可能创建模板元素并用它解析完整 HTML 文档的标记。

const template = document.createElement('template');
template.insertAdjacentHTML('beforeend', '<html></html>');

这个片段将产生DocumentFragment []. head使用完整标记只会产生or元素下方的所有元素body。换句话说:htmlheadbody元素从文档片段中剥离。

这是出乎意料的,MDN 指出

允许内容:无限制

以下是此问题的解决方法。htmlElement包含我template.content在提供完整标记时期望包含的内容。

const htmlElement = document.createElement('html');

const headElement = document.createElement('head');
headElement.insertAdjacentHTML('beforeend', headMarkup);
htmlElement.appendChild(headElement);

const bodyElement = document.createElement('body');
bodyElement.insertAdjacentHTML('beforeend', bodyMarkup);
htmlElement.appendChild(bodyElement);

有什么方法可以创建包含未附加到 DOM 的完整文档的文档片段/元素?

注意:我的用例是将包含完整 HTML 文档的影子 DOM 附加到现有文档的节点。

标签: javascriptdom

解决方案


一种可能的解决方案是DOMParser接口。

const htmlMarkup = `
  <!DOCTYPE html>
  <html>
    <head>
      <title>Title</title>
    </head>
    <body>
      <h1>Hello</h1>
    </body>
  </html>
`;

const parser = new DOMParser();
const doc = parser.parseFromString(htmlMarkup, 'text/html');

const shadowHost = document.querySelector('.shadow-host');
const shadowRoot = shadowHost.attachShadow({ mode: 'open' })
shadowRoot.appendChild(doc.documentElement);

推荐阅读