Question

I'm trying to learn pure Javascript instead of jQuery just to get a hold of what's going on. I don't know why this piece of code doesn't work. It's supposed to add items to a list when you click Add Item

link to fiddle: http://jsfiddle.net/kboucheron/XVq3n/

<input type="text" placeholder ="Add List" id="listItem"/>
<button id="addButton">add Item</button>
<div id="output"></div>

<script>
text = document.getElementById('listItem').value;
addButton = document.getElementById('addButton');

addButton.addEventListener("click", function(e) {
addItem = document.getElementById('output');
        addItem.appendChild(text);
});
</script>
Was it helpful?

Solution

addButton.addEventListener("click", function(e) {
    var text = document.getElementById('listItem').value,
        addItem = document.getElementById('output');
    addItem.appendChild(document.createTextNode(text));
});

http://jsfiddle.net/DerekL/XVq3n/2/

By the way, you have to move the text declaration into the click event listener.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top