In HTML i have input of type text and unordered list. when an enter is hit in the input, the text entered should be grabbed and added to the list. How can i achieve it using javascript without any library?
The below code is what i've written but it not creating the list as expected. it is creating blank li and adding everything to the last li
var newli = document.createElement("li");
var inp = document.getElementsByTagName("input");
var ul = document.getElementsByTagName("ul")[0];
inp[0].addEventListener("keypress", function(event){
if(event.which===13){
var inputText = this.value;
this.value = " ";
var node = document.createElement("LI");
newli.appendChild(document.createTextNode(inputText));
node.appendChild(newli);
ul.appendChild( node );
}
});
<input type="text">
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
</ul>