gpt4 book ai didi

JavaScript ChildNodes 未定义类型错误?

转载 作者:行者123 更新时间:2023-12-01 02:11:19 24 4
gpt4 key购买 nike

您好,我是编码新手,有一个通用问题,我到处查找但找不到解决方案。我正在学习 javascript 教程,并遇到了这一行特定的代码。子节点指出属性“backgroundColor”未定义,我不确定为什么。

错误:“未捕获类型错误:无法设置未定义的属性‘backgroundColor’”

<!doctype html>
<html>
<head>
</head>
<body>


<div id = "sampDiv">

<p> This is a txt field </p>

<p> This is another txt field </p>

</div>



<script>

var sampDiv = document.getElementById("sampDiv");

sampDiv.childNodes[0].style.backgroundColor = "red";
</script>


</body>
</html>

最佳答案

使用children[0]而不是childNodes[0]:

https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children

  var sampDiv = document.getElementById("sampDiv");

sampDiv.children[0].style.backgroundColor = "red";
<!doctype html>
<html>
<head>
</head>
<body>
<div id = "sampDiv">
<p> This is a txt field </p>
<p> This is another txt field </p>
</div>
</body>
</html>

关于JavaScript ChildNodes 未定义类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49745087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com