(or adding HTML tags to the page using JavaScript)
const mySection = document.createElement("section");
mySection.textContent = 'Hello, World'
document.querySelector(".container").appendChild(mySection)
creates the element
tag of the new element
selector for parent
Adds the element to the DOM
The new element
Loops allow us to do the same task repeatedly a controlled amount of times.
- I want to count from 1 to 100 and print out all the even numbers
- While my hand of playing cards totals less than 21, draw a card
- disable all the buttons on the page
for (COUNTER; TILL WHEN; CHANGE COUNTER){
}
// print out the numbers 0-9
for( let i = 0; i <= 9; i++) {
console.log(i)
}
// Count the numbers 1-100,
// if the number is /5 then put in the DOM
for(let i = 1; i <= 100; i++){
if (i % 5 == 0){
const newSpan = document.createElement("span");
newSpan.textContent = i
document.querySelector(".list").appendChild(newSpan)
}
}
while (some_truthy_expression){
// do something
}
let isNightTime = lookOutsideForSun()
while (isNightTime){
// do something
sleep(oneHour)
isNightTime = lookOutsideForSun()
}
// Number
const count = 5;
// string
let dayOfWeek = "Tuesday";
// function
const updateButtonEvent = () => {
console.log("button clicked")
}
// boolean
const isCool = true
const lion1Name = "Simba";
const lion2Name = "Scar";
const lion3Name = "Nala";
const lion4Name = "Mufasa";
const lions = ["Simba", "Nala", "Scar", "Mufasa"]
console.log(lions[2]) // what will this print out?
const myFavoriteThings = []
// add
myFavoriteThings.push('Raindrops on roses')
myFavoriteThings.push('whiskers on kittens')
// add and update
myFavoriteThings[5] = 'Bright copper kettles'
// delete
myFavoriteThings.splice(5,1);
const disneyVillains = ["Jafar", "Scar","Hades", "The Shadow Man"]
for (let i= 0; i < disneyVillains.length; i++){
const listItem = document.createElement('li')
listItem.textContent = disneyVillains[i];
document.querySelector('.villains').appendChild(listItem)
}
But wait! there is more....
const disneyVillains = ["Jafar", "Scar","Hades", "The Shadow Man"]
for (let i= 0; i < disneyVillains.length; i++){
const currentVillain = disneyVillains[i];
const listItem = document.createElement('li')
if (currentVillain === "Hades"){
listItem.classList.add("under-appreciated-villain")
}
listItem.textContent = currentVillain;
document.querySelector('.villains').appendChild(listItem)
}