Lesson 11, Thursday, 2026-04-23
HTML:
<div id="myDiv"></div>How do we change the content of this div?
let myDivElement = document.getElementById("myDiv");
myDivElement.textContent = "Hello world!";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 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:
- Add content or attributes such as
textContent,idandonclick - Apply styles (optional) e.g
style.backgroundColor - Append it to the DOM using
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.
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, thetextContentproperty andappendChild.
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>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.
When the user clicks on a shopping item, remove it from the page.
- Hint: set an
onclickfunction on your newly created HTML element. - Hint: use the
remove()method of your item to remove it.
