未发现NotFoundError:无法在“节点"上执行"insertBefore":要在其之前插入新节点的节点不是该节点的子节点 [英] Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node

查看:932
本文介绍了未发现NotFoundError:无法在“节点"上执行"insertBefore":要在其之前插入新节点的节点不是该节点的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Javascript时遇到问题.我收到此错误消息:

未捕获的NotFoundError:无法在节点"上执行"insertBefore":要在其之前插入新节点的节点不是该节点的子节点.

JavaScript:

var vidCounter = 0;
    vidCounter++;
var originalDiv;
var newVideo = document.createElement("video");
    newVideo.setAttribute("name", vidCounter);
    newVideo.setAttribute("autoplay", "true");
    originalDiv = document.getElementById("othersarea");
    document.body.insertBefore(newVideo, originalDiv); 

它正在尝试在名为othersarea的div下方添加<video>标签.

<div id="remoteVideos">
    <div class="title">
        <h2>Others</h2>
    </div>
    <div id="othersarea">
    </div>
</div>

我该如何解决?

我也想在新的视频代码上运行attachMediaStream([VIDEO TAG HERE HOW?], event.stream);.

解决方案

您必须在之前要插入的元素的父元素上调用insertBefore. document.body不是父级,它在DOM层次结构中遥遥领先.

要在DIV之后插入,必须在下一个同级之前插入.

var parentDiv = document.getElementById("remoteVideos");
parentDiv.insertBefore(newVideo, originalDiv.nextSibling);

请参见 MDN

I am having an issue with Javascript. I'm getting this error message:

Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.

Javascript:

var vidCounter = 0;
    vidCounter++;
var originalDiv;
var newVideo = document.createElement("video");
    newVideo.setAttribute("name", vidCounter);
    newVideo.setAttribute("autoplay", "true");
    originalDiv = document.getElementById("othersarea");
    document.body.insertBefore(newVideo, originalDiv); 

It is trying to add a <video> tag below a div called othersarea.

<div id="remoteVideos">
    <div class="title">
        <h2>Others</h2>
    </div>
    <div id="othersarea">
    </div>
</div>

How do I fix this?

I also want to run attachMediaStream([VIDEO TAG HERE HOW?], event.stream); on my new video tag.

解决方案

You have to call insertBefore on the parent element of the element you're inserting before. document.body is not the parent, it's far up in the DOM hierarchy.

And to insert after a DIV, you have to insert before its next sibling.

var parentDiv = document.getElementById("remoteVideos");
parentDiv.insertBefore(newVideo, originalDiv.nextSibling);

See the examples in MDN

这篇关于未发现NotFoundError:无法在“节点"上执行"insertBefore":要在其之前插入新节点的节点不是该节点的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆