我正在尝试更好地理解JavaScript,并且在创建元素和向其附加值时遇到问题。
我想要做的就是创建一个新的段落元素,它将包含一个新的字符串,并使用appendChild将段落添加到我现有的div标签中。
var oldParagraph = document.getElementById('content')
var newParagraph = document.createElement('p');
var text = document.createTextNode("i am a new text node.");
newParagraph.setAttribute('class', 'red');
function addText(){
document.oldParagraph.appendChild(newParagraph);
document.newParagraph.appendChild(text);
}
我的HTML很简单:
<div id="content"></div>
答案 0 :(得分:3)
您的代码应为:
function addText(){
oldParagraph.appendChild(newParagraph);
newParagraph.appendChild(text);
}
oldParagraph
和newParagraph
是包含DOM对象引用的变量。您直接对这些DOM引用进行操作。
在实践中,我认为你会使用局部变量而不是全局变量来组织你的代码:
function addText() {
var newParagraph = document.createElement('p');
newParagraph.className = 'red';
newParagraph.appendChild(document.createTextNode("i am a new text node."));
document.getElementById('content').appendChild(newParagraph);
}