![](/img/trans.png)
[英]Failed to execute 'appendChild' on 'Node': Nodes of type 'a' may not be inserted inside nodes of type 'LI'
[英]Nodes of type '#document' may not be inserted inside nodes of type 'HEAD'
我正在尝试在 HEAD 中动态添加一些脚本
const parser = new DOMParser();
const scripts = parser.parseFromString("<script>console.log('hello world')</script><noscript>console.log('hello world')</noscript>", 'text/xml');
const doc = scripts.getRootNode();
document.getElementsByTagName('head')[0].appendChild(doc);
这是我收到的错误HierarchyRequestError: Failed to execute 'appendChild' on 'Node': Nodes of type '#document' may not be inserted inside nodes of type 'HEAD'.
这就是我所做的
const parser = new DOMParser();
const scripts = parser.parseFromString("<script>console.log('hello world')</script><noscript>console.log('hello world')</noscript>", 'text/xml');
const doc = scripts.getRootNode();
(doc as any).head.childNodes.forEach(c => {
document.getElementsByTagName('head')[0].appendChild(c);
});
如果有人有更好的答案,我会很乐意接受
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.