简体   繁体   English

未捕获的TypeError:无法调用null的方法'replaceChild'

[英]Uncaught TypeError: Cannot call method 'replaceChild' of null

I've been trying to make this work for hours. 我一直在努力使这项工作工作数小时。 None of the documentation or answers here have helped yet. 这里的文档或答案都没有帮助。

I'm trying to replace each item in the flippedCards array with an empty div. 我试图用一个空的div替换flippedCards数组中的每个项目。

Getting the parent works fine, it gives back a div element. 使父级工作正常,它会返回一个div元素。 The error is when asking for the child, it says it's null, or sometimes undefined. 错误是在询问孩子时,它说它为null或有时未定义。

There's only two items with the class of "flip". “翻转”类只有两个。

I only want to use JS. 我只想使用JS。

HTML 的HTML

<div>
    <div class="flip">
        <div></div>
        <div></div>
    </div>
    <div class="flip">
        <div></div>
        <div></div>
    </div>
</div>

JS JS

var flippedCards = document.querySelectorAll('.flip');

var replaceCards = document.createElement("div");

while (flippedCards[0] && flippedCards[1]) {
flippedCards[0].parentElement.replaceChild(replaceCards, flippedCards[0])          
flippedCards[1].parentElement.replaceChild(replaceCards, flippedCards[1]);
}

Try this : 尝试这个 :

var flippedCards = document.querySelectorAll('.flip');
var replaceCards = document.createElement("div");

flippedCards[0].parentElement.replaceChild(replaceCards, flippedCards[0]);
replaceCards = document.createElement("div");       
flippedCards[1].parentElement.replaceChild(replaceCards, flippedCards[1]);

Someone answered it then they deleted their answer. 有人回答了,然后他们删除了答案。 Was a two piece mistake on my part. 我有两个错误。 Was wrapped in a while loop to check if those values existed in the first place. 被包装在while循环中,以检查这些值是否首先存在。 Then I didn't make two replaceCards. 然后我没有做两张replaceCard。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的TypeError:无法调用null的方法“ appendChild”? - Uncaught TypeError: Cannot call method 'appendChild' of null? 未被捕获的TypeError:无法调用null的方法&#39;getElementsByTagName&#39; - Uncaught TypeError: Cannot call method 'getElementsByTagName' of null 未捕获的TypeError:无法调用null的方法“ menuAim” - Uncaught TypeError: Cannot call method 'menuAim' of null 未捕获的TypeError:无法调用null的方法'replace' - Uncaught TypeError: Cannot call method 'replace' of null 未捕获的TypeError:无法调用null的方法“ show” - Uncaught TypeError: Cannot call method 'show' of null 未捕获的TypeError:无法调用null的方法“ get” - Uncaught TypeError: Cannot call method 'get' of null 未捕获的TypeError:无法调用null的方法“提交” - Uncaught TypeError: Cannot call method 'submit' of null XML,JavaScript-未捕获的TypeError:无法调用方法&#39;getElementsByTagName&#39;为null - XML, Javascript - Uncaught TypeError: Cannot call method 'getElementsByTagName' of null 如何修复“Uncaught TypeError:无法调用方法&#39;appendChild&#39;的null” - How to fix “Uncaught TypeError: Cannot call method 'appendChild' of null” 未捕获的TypeError:无法调用null的方法“ terminate”(网络工作者) - Uncaught TypeError: Cannot call method 'terminate' of null (web worker)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM