Skip to content

Latest commit

 

History

History
144 lines (94 loc) · 3.14 KB

File metadata and controls

144 lines (94 loc) · 3.14 KB

JavaScript Course - Spring 2026

Lesson 11, Thursday, 2026-04-23


Recap - get Element By Id

HTML:

<div id="myDiv"></div>

How do we change the content of this div?

let myDivElement = document.getElementById("myDiv");
myDivElement.textContent = "Hello world!";

Recap - button click event Element By Id

HTML:

<button id="aButton"></button>

JS:

function handleClickButton() {
    console.log('button clicked')
}

How do we attach handleClickButton to the button element?

<button id="aButton" onclick="handleClickButton()"></button>

document.createElement

document.createElement is used to create a new HTML elemen (such as div, img, button) using JavaScript. It's the first step in building elements dynamically.

Basic usage:

let myDiv = document.createElement("div");

This creates a new <div> element in memory, but it's not visible on the page yet.

However, we need to do a bit more configuration to have something useful.


let myDiv = document.createElement("div"); // 1
myDiv.textContent = "hello";               // 2
document.body.appendChild(myDiv);          // 3
// <div>hello</div> has been added to the page!

To make it useful, we typically need to:

  1. Add content or attributes such as textContent, id and onclick
  2. Apply styles (optional) e.g style.backgroundColor
  3. Append it to the DOM using appendChild().

.appendChild()

appendChild are used to add elements to the DOM, that is, to make them appear on the page.

document.body.appendChild(myDiv);

appendChild can be called on almost any element.

Remember our <body> tag in the html? document.body refers to that element; it is mostly just like any other HTML element. Everything inside the <body> is what the user sees in the browser.


Task 1: Appending elements

Let's say you have this HTML:

<div id="myDiv"></div>

How do you turn it to this from JavaScript?

<div id="myDiv">
    <span>Hello</span>
</div>
  • Hint: Use document.getElementById, document.createElement, the textContent property and appendChild.

Task 2

Create a button at the top of the page that generates a new element in sequence when clicked, so "Element 1", "Element 2", and so on.

Example:

<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div>Element 4</div>
<div>Element 5</div>

Task 3: Create a shopping list app!

It should have one <input> field where the user can enter a shopping item. It should have one <button>. When the user clicks the button, the text from the <input> field should be appended to the shopping list.

Page


Bonus (difficult!!!)

When the user clicks on a shopping item, remove it from the page.

  • Hint: set an onclick function on your newly created HTML element.
  • Hint: use the remove() method of your item to remove it.