Creating Elements
So far, you've changed elements that were already in index.html. JavaScript can also create new ones. Lists are a good example. In HTML, a list is the ul element, and each item is an li element inside it:
<ul id="fruits">
<li>Apple</li>
<li>Pear</li>
</ul>Adding an item takes three steps:
const fruitList = document.querySelector("#fruits");
const item = document.createElement("li");
item.textContent = "Banana";
fruitList.append(item);document.createElement("li")creates a newlielement. So far, it exists only in the program; it isn't on the page.textContentsets its text.fruitList.append(item)puts the element into the list, at its end. Only now does it appear on the page.
The list now has three items: Apple, Pear and Banana. A typical mistake is to forget the last step: the element is created, but nobody puts it into the page, so you can't see it.
Each new item needs its own createElement(). An element can be on the page only once: if you append() the same element again, you don't get a copy; the element just moves to the end. So when a button should add a new item on every click, create the element inside the handler.
On the internet, you'll often see innerHTML used to put content into an element. Don't use it with text the user typed: it reads the text as HTML, so the text could break the page or even run code that someone slipped into it. createElement() and textContent always show text just as text.
Instructions
Add a guest Lucy to the end of guestList: create an li element, set its text to Lucy and append it to the list.
When addButton is clicked, add a new guest to the end of the list, with the name typed into guestInput. Try adding a few guests.
Start programming for free
8/10