Javascript document.getElementById调试
我试图练习Javascript,但我得到了 document.getElementById(…)为空错误。我不知道它为什么不起作用Javascript document.getElementById调试,javascript,Javascript,我试图练习Javascript,但我得到了 document.getElementById(…)为空错误。我不知道它为什么不起作用 <!DOCTYPE html> <html> <title></title> <head> <meta charset="utf-8"> <meta name="viewport" content="wid
<!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>
window.onload=函数create(){
var newDiv=document.createElement('div');
var newp=document.createElement('p');
var pTextNode=document.createTextNode('第一次自己创建元素');
newDiv.className='contentContainer';
newDiv.id='container1';
newDiv.setAttribute('title','hello');
newp.appendChild(pTextNode);
newDiv.appendChild(newp);
document.getElementById(“实践”).appendChild(newDiv);
}
document.getElementByIdAPI将ID参数作为字符串。您不需要使用选择ID的CSS选择器方法,因此应该省略
。该行应为:
document.getElementById("practice").appendChild(newDiv);
有关API的更多信息,请参见所有内容都正确!问题在于
getElementById
方法中的语法。移除octothorpe(“#”)将得到预期的结果
快乐编码 删除
符号,这样它就是文档。getElementById(“实践”)
在调用getElementById
时删除
。谢谢