Your're going to code a solution to the TODO list during livecode so no lecture code today 😢
Here are a few takeways and snipplets from the lecture:
document.querySelector(CSS_SELECTOR)
, where CSS_SELECTOR is any valid css selector that you use in css files. Similar to Ruby's find
, it returns an element (returns 1 thing only).
document.querySelector('ul > li') // returns the first li in the ul
document.querySelectorAll(CSS_SELECTOR)
, similar to Ruby's select
, it returns an Array-like object (called a Nodelist).
document.querySelectorAll('ul > li') // returns all the li in the ul
Syntax: () => {}
Arrow functions don't have a name, so we store them in const variables.
const renderTodo = (todo, index) => {
// Do/return something
};
Syntax: element.insertAdjacentHTML(position, htmlString)
This will insert an htmlString in the position relative to the element
const todosList = document.querySelectorAll('ul');
todosList.insertAdjacentHTML('afterbegin', '<li>Hello, I am a TODO</li>');
querySelectorAll
returns a nodelist, which is an Array-like object that can be iterated over with forEach:
const listItems = document.querySelectorAll('ul > li');
listItems.forEach((listItem) => {
// Do something with each listItem HTML element
});
Syntax: element.addEventListener(eventType, callback)
eventType: a string specifying the event, some of the most common are the 'click'
event and the form 'submit'
event;
callback: a function that will only be executed when the event is TRIGGERED/FIRED/EMITTED (they mean the same here);
const form = document.querySelector('form');
form.addEventListener('submit', () => {
// Do something when the form is submitted
});
NOTE: Because form submits reload or navigate away the current page, it is common to pass the event
object to the CALLBACK:
form.addEventListener('submit', (event) => {
event.preventDefault();
// This stops the default behaviour of the (form) element,
// i.e., stops the reloading/navigating away from the current page
// Then do something
});
When we have several elements that should receive the same event listeners, a typical pattern is to iterate over them and attach the event listener for each one of them:
const listItems = document.querySelectorAll('ul > li');
listItems.forEach((listItem) => {
listItem.addEventListener('click', () => {
// Do something when each listItem is clicked!
})
});