I have a nice, working and functional to-do list. However, in practice (using it on a phone), the new items added to the list are hidden by the keyboard. So I want to have the list add every item to the beginning, or top of the list, so that new items are seen as they are created.
Enter "insertBefore()", which works fine as long as there is a child to insert before, otherwise it throws an error.
How would you have this work with an empty list? Just do an "if there are no child elements, do this - else - do that" or is there a simple addition to the process?
var inputText = document.getElementById("textField");
var myUl = document.getElementsByTagName("ul");
inputText.addEventListener("keypress", function(event){
if( event.keyCode === 13){
var myInputText = this.value;
var listItem = document.createElement("li");
var spanItem = document.createElement("span");
var theText = document.createTextNode(myInputText);
var span_img = document.createElement("img");
span_img.src = "images/trashCanBlack.png";
spanItem.appendChild(span_img);
listItem.appendChild(spanItem);
listItem.appendChild(theText);
myUl[0].appendChild(listItem); // this works, but only adds it on the end
this.value = "";
}
});
So I want to have the list add every item to the beginning, or top of the list...
Believe it or not, it's this easy:
myUl[0].insertBefore(listItem, myUl[0].firstChild);
It's fine if myUl[0]
is empty (and thus its firstChild
is null
). insertBefore
is smart enough to handle that (by effectively being appendChild
).
Side note: Rather than doing:
var myUl = document.getElementsByTagName("ul");
...and then using myUl[0]
everywhere, you might consider either:
var myUl = document.querySelector("ul"); // returns the first one
or
var myUl = document.getElementsByTagName("ul")[0];
...and then just using myUl
.