jsMess jsMess - 1 year ago 55
HTML Question

Getting an element by id and then storing it in a variable to then be appended to an li?

new to JS here and trying to create a basic to-do list. I've gone through CodeAcademy and TreeHouse tutorials and understand functions, if statements, loops, objects etc but what I find is until you attempt to create your own project you realise none of it has actually sunk in!

So I'm currently trying to build up a basic to-do list that will eventually let me add new tasks, mark tasks as finished etc. I know there's tutorials on the web, but without creating it myself I don't think I'll learn.

So, I'm getting the value typed into the element named "taskField" and storing it in a variable called task:

var task = document.getElementById("taskField");

Then, I am creating a function called addTask():

function addTask() {
var liNode = document.createElement("li"); // Creates an li tag and sets it as a variable known as liNode
liNode.appendChild(task); // Appends liNode to the value of the variable task declared above
document.getElementById("taskList").appendChild(liNode); // Gets the ul and adds the li item

The function is called when the button is clicked, here's my jsfiddle so you can see all my HTML markup as well: https://jsfiddle.net/3b5rprx0/

So, what am I doing wrong here?


Answer Source

The mistake you have done is,

1) You were trying to add the entire textbox into the 'li' element.
Instead you need to get its value using 'value' property.

It shoud be like,

var task = document.getElementById("taskField").value;
var liNode = document.createElement("li");

I have changed the code. Have a look at it. https://jsfiddle.net/gox8x6ot/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download