I'm trying to create a function in which a user clicks a button in order to add an item to an unordered list of items (without using jQuery). This is my js code:
window.onload = function(){ document.body.addEventListener("click", function(event) { if (event.target.id == "add-item") var item = prompt(); /** returns a string variable */ var itemlist = document.getElementById("items"); console.log(typeof itemlist); /** returns an object*/ // itemlist.createElement("li"); /** A node is the generic name for any type of object in the DOM hierarchy. */ }); }
<ul id="items"> <li>The first item is free!</li> </ul> <button type="button" id="add-item">Add item</button>
Currently i get the following error:
Uncaught TypeError: itemlist.createElement is not a function at HTMLBodyElement.
Note that i have also tried using querySelector to get the list of items, as well as the function appendChild() on the item-list, but none of it works...
Any help or suggestions are much appreciated!
createElement
is a method of the document
object. After you have created it, you can append it to another element.
var list_item = document.createElement("li");
itemlist.appendChild(list_item);
createElement
is a function on document
, not on itemlist
.
Use this instead:
var li = document.createElement("li");
li.innerHTML = item; // Set the text from the propt's return value.
itemlist.appendChild(li);
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.