Vanilla JavaScript Flashcards
How do you throw an error?
throw new Error(‘this is the error’)
How do you add JavaScript to html?
<head>
</head>
How do you reference a DOM element by its ID?
document.getElementById(‘my-id’);
How do you reference a DOM element by a CSS selector (both first element or all elements)?
document.queySelector(‘div’);
const divItems = document.querySelectorAll(‘div’);
// can then iterate through divItems using forEach or reference elements like divItems[1]
How do you reference a DOM element by its CSS class?
document.getElementsByClassName(‘my-class’);
How do you change the styling of an element, like color?
const item = getElementById(‘my-id’);
item.style.color = ‘blue’
OR
item.setAttribute(‘color’, ‘blue’);
// generally shouldn’t do this; should set with CSS instead
How do you change the text of an element?
element.textContent = ‘My new content’;
OR
element.setAttribute(‘textContent’, ‘My new content’);
How do you add and remove CSS classes to an element?
element.classList.add(‘my-class’, ‘my-second-class’);
element.classList.remove(‘my-class’);
How do you create a new DOM node, like paragraph?
const p = document.createElement(‘p’);
p.textContent = ‘Hello’;
document.body.append(p); // can also .prepend(p)
How do you create multiple new DOM nodes at once, like list items?
const parent = document.querySelector(‘ol’);
const fragment = document.createDocumentFragment();
for (let i = 0; i < 3; i++) {
const li = document.createElement(‘li’);
li.textContent = List item ${i}
;
fragment.append(li);
}
parent.append(fragment);
How do you delete an element from the DOM?
element.remove();
How do you get the list items within a ul with an id of ‘my-id’?
const ul = document.getElementById(‘my-id’);
const listItems = ul.querySelectorAll(‘li’);
How would you log to the console if a button was clicked?
const button = document.querySelector(‘button’);
const onClick = () => console.log(‘you clicked the button’);
button.addEventListener(‘click’, onClick);
// can remove event listener with button.removeEventListener(‘click’, onClick);
// double click is ‘dblclick’
How would you create an event listener for any key that is clicked?
window.addEventListener(‘keydown’, (event) => { … })
How do you create a promise?
const promise = new Promise((resolve, reject) => {
resolve(someValue);
// reject(new Error(‘something went wrong’))
})
promise.then(value => console.log(value)).catch(error => console.log(error))
// a promise is in a “pending” state until it is either resolved (“fulfilled”) or rejected
// you can also chain thens, eg
promise
.then(value => value * 2)
.then(value => value + 1)
.then(value => console.log(value))
.catch(error => console.log(error))
.finally(() => console.log(‘done’))
// finally will always run; it doesn’t take a parameter