【问题标题】: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未捕获的 NotFoundError:无法在“节点”上执行“插入前”:要插入新节点的节点不是该节点的子节点
【发布时间】:2014-06-17 13:46:17
【问题描述】:

我遇到了 Javascript 问题。我收到此错误消息:

Uncaught NotFoundError: Failed to execute 'insertBefore' on '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); 

它试图在一个名为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);

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你必须在你之前插入的元素的父元素上调用insertBeforedocument.body 不是父级,它在 DOM 层次结构中很靠前。

    要在 DIV 之后插入,您必须在其下一个兄弟之前插入。

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

    查看MDN中的示例

    【讨论】:

    • 感谢您的快速回复。现在我明白了:TypeError: Cannot read property 'nextSibling' of undefined
    • 这意味着getElementById 找不到ID。确保在加载 DOM 后运行代码,例如它应该在事件处理程序中或window.onload.
    【解决方案2】:

    尝试使用parentNode

    originalDiv.parentNode.insertBefore(newVideo, originalDiv); 
    

    这将直接在 originalDiv 前面插入 newVideo。

    原因是node.insertBefore(newNode, existingNode) 使用node 作为对existingNode 周围元素的引用。

    参考:http://www.w3schools.com/jsref/met_node_insertbefore.asp

    这也是 Google Analytics(分析)的作用: http://www.stevesouders.com/blog/2010/05/11/appendchild-vs-insertbefore/

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      相关资源
      最近更新 更多