如何清空 div 的内容并插入有效的 iFrame?
How to empty the contents of a div and insert a working iFrame?
我正在尝试创建一个清空其内容(缩略图/播放按钮)的视频容器并将其替换为 iframe 的功能,例如 vimeo 或 youtube。
到目前为止我得到了这个:
replaceIframe(){
const parser = new DOMParser();
const videoContainer = document.querySelector('#landingspage .video-container');
const iframe = document.querySelector('#landingspage .iframe-container').innerHTML;
const iframeHTML = parser.parseFromString(iframe, "text/html");
console.log(iframeHTML);
if(videoContainer !== null){
videoContainer.addEventListener('click', (ev) => {
ev.preventDefault();
videoContainer.replaceChildren(iframeHTML);
});
}
}
但这给了我错误:
Uncaught DOMException: Failed to execute 'replaceChildren' on 'Element': Nodes of type '#document' may not be inserted inside nodes of type 'DIV'.
at HTMLDivElement.
我该如何解决这个问题?我首先在没有解析器对象的情况下尝试了它,但随后它只是用 iframe html.
的字符串替换了内容
使用videoContainer.innerHTML = iframeHTML
代替videoContainer.replaceChildren(iframeHTML)
;
我正在尝试创建一个清空其内容(缩略图/播放按钮)的视频容器并将其替换为 iframe 的功能,例如 vimeo 或 youtube。
到目前为止我得到了这个:
replaceIframe(){
const parser = new DOMParser();
const videoContainer = document.querySelector('#landingspage .video-container');
const iframe = document.querySelector('#landingspage .iframe-container').innerHTML;
const iframeHTML = parser.parseFromString(iframe, "text/html");
console.log(iframeHTML);
if(videoContainer !== null){
videoContainer.addEventListener('click', (ev) => {
ev.preventDefault();
videoContainer.replaceChildren(iframeHTML);
});
}
}
但这给了我错误:
Uncaught DOMException: Failed to execute 'replaceChildren' on 'Element': Nodes of type '#document' may not be inserted inside nodes of type 'DIV'.
at HTMLDivElement.
我该如何解决这个问题?我首先在没有解析器对象的情况下尝试了它,但随后它只是用 iframe html.
的字符串替换了内容使用videoContainer.innerHTML = iframeHTML
代替videoContainer.replaceChildren(iframeHTML)
;