javascript - 从完整的 HTML 标记创建模板元素/文档片段
问题描述
似乎不可能创建模板元素并用它解析完整 HTML 文档的标记。
const template = document.createElement('template');
template.insertAdjacentHTML('beforeend', '<html></html>');
这个片段将产生DocumentFragment []
. head
使用完整标记只会产生or元素下方的所有元素body
。换句话说:html
、head
和body
元素从文档片段中剥离。
这是出乎意料的,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 附加到现有文档的节点。
解决方案
一种可能的解决方案是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);
推荐阅读
- angular - 通过 REST Api 下载 CSV
- reactjs - 将回调传递给第三方库时出现意外
- java - 带有 JWT 令牌的 Spring Security 在每个请求上加载 spring UserDetails 对象
- java - 在 6 次迭代后,在 for 循环中为 double 分配新值
- django - 添加 Django 缓存中间件的正确顺序是什么?
- c# - 在固定时间内读取串行数据的最有效方式
- reporting-services - SSRS 报告将外部文件插入到最终的 pdf 报告中
- asp.net-mvc - ASP.net 2.2 MVC:注销
- javascript -
- batch-file - 输出:“此时出乎意料”,这段代码有什么问题?