在新创建div内使用appendChild时遇TypeError错误求助
问题分析与解决办法
哦,我一眼就揪出问题所在啦!你遇到的Uncaught TypeError: Cannot read property 'appendChild' of undefined错误,根源出在这一行代码上:
document.cClause1.appendChild(right_clause_1); //Error occurs here!
错误原因
你可能误以为cClause1是document对象的属性,但实际上cClause1是你自己用const cClause1 = document.getElementById("container_clause_1");定义的独立变量,它并不属于document。所以document.cClause1会返回undefined,对undefined调用appendChild自然就会抛出类型错误。
你完全不需要在cClause1前面加document,直接用你已经获取到的变量就可以了:
cClause1.appendChild(right_clause_1); // 这样就不会报错啦
更优的写法(就是你后来优化的版本)
其实你后续调整的代码是更高效的做法!既然你在创建container_clause_1的时候已经拿到了它的引用,完全没必要再用getElementById去DOM树里重新查找一遍——直接用内存里的变量操作就行,既减少了DOM查询的性能开销,也避免了不必要的代码冗余。
优化后的代码逻辑非常清晰:
const container_clause_1 = document.createElement("div"); document.body.appendChild(container_clause_1); container_clause_1.setAttribute("id", "container_clause_1"); container_clause_1.classList.add("cc1"); const right_clause_1 = document.createElement("div"); container_clause_1.appendChild(right_clause_1); // 直接用创建时的变量,一步到位 right_clause_1.setAttribute("id", "right_clause_1"); right_clause_1.classList.add("r1");
内容的提问来源于stack exchange,提问作者user6095724
相关产品推荐
相关产品推荐

