admin管理员组文章数量:1322850
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
1 Answer
Reset to default 7It'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
本文标签: Appending an li to ul with vanilla JavaScriptStack Overflow
版权声明:本文标题:Appending an li to ul with vanilla JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742112936a2421333.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论