gpt4 book ai didi

Javascript document.getElementById 调试

转载 作者:行者123 更新时间:2023-11-29 20:58:09 24 4
gpt4 key购买 nike

我正在尝试练习 Javascript,但我得到了document.getElementById(...) 为空错误。我不确定为什么它不起作用。 ..................................................... ..................................................... ..................................................... ..................................................... ...........................................

    <!DOCTYPE html>

<html>

<title></title>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body style="max-width: 960px; margin: 0px auto; background-color: green;">
<section id="practice">

</section>
</body>
<script>

window.onload = function create() {

var newDiv = document.createElement('div');
var newp = document.createElement('p');
var pTextNode = document.createTextNode('First time creating elements on my own.');

newDiv.className = 'contentContainer';

newDiv.id = 'container1';

newDiv.setAttribute('title', 'hello');


newp.appendChild(pTextNode);
newDiv.appendChild(newp);

document.getElementById("#practice").appendChild(newDiv);

}
</script>
</html>

最佳答案

document.getElementById API 将 ID 参数作为字符串。您不需要使用 CSS 选择器方法来选择 ID,因此应省略 #。该行应为:

document.getElementById("practice").appendChild(newDiv);

有关 API 的更多信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

关于Javascript document.getElementById 调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48198008/

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