最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Appending an li to ul with vanilla JavaScript - Stack Overflow

programmeradmin4浏览0评论

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);

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);
Share Improve this question asked Sep 19, 2014 at 18:23 Tim AychTim Aych 1,3654 gold badges17 silver badges34 bronze badges 1
  • @Teemu because $() is typical jQuery selector syntax. – BenM Commented Sep 19, 2014 at 18:27
Add a ment  | 

1 Answer 1

Reset to default 7

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

发布评论

评论列表(0)

  1. 暂无评论