Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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);
  1. document.createElement("li") creates a new li element. So far, it exists only in the program; it isn't on the page.
  2. textContent sets its text.
  3. 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

  1. 1

    Add a guest Lucy to the end of guestList: create an li element, set its text to Lucy and append it to the list.

  2. 2

    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.

Back

8/10

  1. 1. JavaScript in a Web Page
  2. 2. Finding Elements
  3. 3. When Nothing Is Found
  4. 4. Changing Styles
  5. 5. Reacting to Clicks
  6. 6. A Click Counter
  7. 7. Text Fields
  8. 8. Creating Elements
  9. 9. Showing an Array
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.