I am trying to understand JavaScript a little better and am having trouble creating elements and appending values to them.
All I want to do is create a new paragraph element, which will contain a new string, and add the paragraph to my existing div tag using appendChild.
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);
}
my HTML is simple:
<div id="content"></div>
Your code should be this:
oldParagraphandnewParagraphare variables containing DOM object references. You operate on those DOM references directly.In practice, I would think you’d organize your code more like this with local variables instead of global variables:
Working demo: http://jsfiddle.net/jfriend00/42ffq/.