li_13579_li
li_13579_li
2018-12-30 11:23

为什么使用Node.replaceChild报Uncaught TypeError: Cannot read property 'replaceChild' of null

5
  • css
  • html5
  • javascript

图片说明

代码在下面:


<div class="parent">
    <div class="child">
        <p>学习Java</p>
    </div>
</div>


<script type="text/javascript">
    var newElement = document.createElement("h1");
    newElement.textContent = "学习JavaScript";

    var oldElement = document.querySelector("p");
    oldElement.parentNode.replaceChild(newElement,oldElement);

    console.log(newElement); //Chrome输出: <h1>学习JavaScript</h1>
    console.log(oldElement); //Chrome输出: <p>学习Java</p>
    console.log(oldElement.parentNode.replaceChild(newElement,oldElement)); //Uncaught TypeError: Cannot read property 'replaceChild' of null

</script>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答