简体   繁体   中英

Appending an li to ul with vanilla JavaScript

I'm having trouble with a really simple script, consisting of a text box, button, and list of items. Clicking the button adds the text box value to the list. For some reason, though, the text is getting appended as pure text, and not inside of an li element. JSFiddle

 <form>                      

     <input type="text" class="form-control" placeholder="Task" id="text_task">

   <button type="submit" id="btn_add_task" class="btn btn-primary">Add Task</button>

</form>           

<ul id = "list_tasks">

</ul>      

JS:

function $(element) {
    return document.getElementById(element);
}

var taskSubmit = $('btn_add_task');
var taskBox = $('text_task');
var taskList = $('list_tasks');

taskSubmit.addEventListener('click', function(e) {
    e.preventDefault();
    var task = taskBox.value.trim();

    var newLI = document.createElement('li');
    var element = newLI.appendChild(document.createTextNode(task));

    taskList.appendChild(element);

    taskBox.value = '';

}, false);

It's because you're returning the textNode to element when you should be appending newLI

var newLI = document.createElement('li');

newLI.appendChild(document.createTextNode(task));

taskList.appendChild(newLI);

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM