JS230 Flashcards
Front-end development with JavaScript!
What is the DOM?
The DOM is an in-memory object representation of an HTML document.
What is the purpose of the DOM?
The DOM provides the functionality needed to build modern interactive user experiences.
What is document
?
document
is the top-most DOM node that represents the entire HTML document.
Node.nodeName
Returns the name of the current node as a string.
What does the .nodeName
property for elements return?
Returns the name of the corresponding tag in uppercase. EX: ‘P’ for paragraph.
Node.nodeType
Returns a number that returns a node type constant.
How would you determine if a node was an element node?
Use a comparison expression comparing node.nodeType
to Node.ELEMENT_NODE
.
How would you determine if a node was a text node?
Use a comparison expression comparing the node.nodeType
to Node.TEXT_NODE
.
An element node’s .nodeValue
property returns….
null
Node.nodeValue
Returns the value of a node.
A text node’s .nodeValue
property returns…
The textual content of the node.
What does the .textContent
property return for element nodes?
The .textContent
property returns a string of all the textual content of all the nodes inside the element.
Element
nodes represent…
HTML tags.
The best way to determine a node’s type from the console is…?
node.toString()
which will allow you to read the node’s name.
The best way to determine an Element
node’s type (tag it represents from HTML) in a program is…?
Use the instanceof
operator.
EX: node instance of HTMLParagraphElement
Node.childNodes
Returns a collection of the calling node’s children.
Node.firstChild
Returns the calling node’s first child OR null
.
Node.lastChild
Returns the calling node’s last child OR null
.
Node.parentNode
Returns the calling node’s parent node OR null
if the topmost node.
A live collection…
automatically updates to reflect changes in the DOM.
Node.nextSibling
Returns the node’s next sibling OR null
.
Node.previousSibling
Returns the node’s previous sibling OR null
.
What are HTML attributes?
Elements in HTML have attributes. Attributes are values that configure the elements or adjust their behavior in various ways to meet the criteria that users want.
Node.getAttribute()
Retrieves the value of the node instance’s attribute passed as an argument.
Node.setAttribute()
Sets the value of the node instance’s attribute (1st arg) to the value of the 2nd argument.
Node.hasAttribute()
Determines if the node instance has the attribute passed as an argument and returns an appropriate boolean value.
Reminder: There is a warning about using .setAttribute
to modify value
in XUL.
https://launchschool.com/lessons/ba24c7d4/assignments/c4315283#:~:text=When%20using%20setAttribute%20please%20take%20note%20of%20this%20warning%20from%20MDN
The DOM exposes special attributes as properties of the Element. What are these properties?
id
, name
, title
and value
Note: these properties can be accessed and reassigned using standard property access.
*these properties are only available on very select Elements.
Element.classList
property references…
A special array-like DOMTokenList
object that exposes useful properties and methods for working with an Element’s class(es).
Element.classList.add()
Adds a class name to an element
Element.classList.remove()
Removes a class list from an element.
Element.classList.toggle()
Adds a class to an element if it doesn’t exist and removes the class if it does.
Element.classList.contains()
Determines if the element has a class and returns an appropriate boolean.
Element.classList.length
Returns the number of classes to which the element belongs.
Element nodes have a style attribute accessible via Element.style
that references…
A CSSStyleDeclaration
Object:CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", ...}
To remove a CSS property…
set the property to null
via Element.style
Node.getElementsByTagName(tagName)
Returns an array-like collection of matching elements that are within the calling node.
Node.getElementsByClassName(className)
Returns an array-like collection of matching elements that are within the calling node.
The most common CSS selectors that we will use include:
Element type (‘p’, ‘h1’…), class name (‘.className’), and id (‘#idValue’)
Node.querySelector(selectors)
Returns the first matching element within the calling node OR null
*Can take multiple selectors as an argument EX: ‘‘#divTwo, #divOne’ and returns the first matching element.
Node.querySelectorAll(selectors)
Returns an array-like collection of matching elements within the calling node.
Element.children
Returns a live collection of all child elements.
Node.firstElementChild
Returns the first child element OR null
Node.lastElementChild
Returns the last child element OR null
Node.childElementCount
Returns the number of children elements
Element.nextElementSibling
Returns the next element sibling OR null
Element.previousElementSibling
Returns the previous element sibling OR null
The best strategy for updating text with JavaScript is to…
WHY?
Place the text you need to update within an element. The element type doesn’t matter (could be a bare span or div). This is because when you reassign the Element.textContent
doing so removes all child nodes from the element and replaces them with a text node.
document.createElement(tagName)
Method creates the HTML element specified by tagName
Node.appendChild(node)
Adds a node to the end of the calling node’s children.
** use document.body.appendChild
if need to insert to body.
document.createTextNode(text)
Creates a new text node.
Node.cloneNode(deepClone)
If deepClone is true
, cloneNode
will create copies of the calling node and all descendent nodes! Otherwise will only copy calling node.
*Always provide an appropriate boolean argument value!
Node.insertBefore(node, targetNode)
Insert node
into node.childNodes
BEFORE targetNode
.
Node.replaceChild(node, targetNode)
Remove targetNode
from node.childNodes
and insert node
in its place.
No Node may appear twice in the DOM. Thus….
you can move an existing node by inserting it where you want it.
element.insertAdjacentElement(position, newElement)
Inserts newElement
at position
relative to element
.
element.insertAdjacentText(position, text)
Inserts a Text node that contains text
at position
relative to element
.
Valid position
string values for Element insertion methods:
“beforebegin” -> Before the element
“afterbegin” -> Before the first child of the element
“beforeend” -> After the last child of the element
“afterend” -> After the element
node.remove()
Removes node
from DOM
node.parentElement
Returns the node’s parent element OR null
setTimeout()
Takes a callback and a number representing a timer in milliseconds, the callback is invoked only after the timer completes.
The timer starts once the primary JS file has finished execution. If no number provided default is 0, effectively executing the callback once the primary JS file has finished.
setInterval
Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
Event.type
Returns the name of the event.
Event.currentTarget
Returns the current object that the event object is on. It always refers to the element that has the event listener attached to it.
Event.target
The object on which the event occurred
EX: the element clicked by the user.
During the capturing phase of an event, the event travels…
down to the target element.
During the bubbling phase of an event, the event travels from….
the target element through containing elements.
.addEventListener()
Sets up a function that will be called whenever the specified event is delivered to the target.
EventTarget.addEventListener(type, listener, useCapture)
*useCapture defaults to false unless specified otherwise.
event.stopPropogation()
Stops the event
object from continuing its path along the capturing and bubbling phases.
event.preventDefault()
Directs the browser to NOT perform any actions that it might otherwise perform in response to a user’s actions.
It’s good practice to call preventDefault
or stopPropagation
as soon as possible in an event handler. Doing so emphasizes the presence of those methods to people reading the code. It also ensures that these methods run before any errors occur; not running these methods before an error occurs can lead to unexpected behavior that is hard to debug.
How do you implement event delegation?
Event delegation involves adding a single listener to any common ancestor of the elements you want to watch.
Promise.all()
Takes an array of promises as an argument and returns a single promise. The returned promise resolves when all of the input promises resolve, or rejects as soon as one of the input promises rejects.
If the returned promise resolves, it resolves with an array containing the resolve values of each promise, in the same order as provided.
Promise.race()
Takes an array of promises as an argument and returns a single promise that settles as soon as one of the input promises settles (is either resolved or rejected). This is useful when you only care about the first promise to complete.
Promise.allSettled()
Takes an array of promises and returns a single promise that resolves after all of the input promises have either resolved or rejected. The returned promise settles with an array of objects that describes the outcome of each promise.
Promise.any()
Promise.any() takes an array of Promise objects and, as soon as one of the promises in the array fulfills, it returns a single promise that resolves with the value from that promise. If no promises in the array fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new error type that groups together individual errors.
Node.prototype.contains
Returns a boolean value indicating whether a node is a descendant of a given node, that is the node itself, one of its direct children (childNodes), one of the children’s direct children, and so on.
What is the value of this
within an event handler function?
Event.currentTarget
What are some benefits of event delegation?
1) Makes code easier to maintainable by reducing the number of event listeners.
2) Allows developer to add event listener to an element that is not yet present in the DOM.
What is asynchronous JavaScript?
Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.
What does the DOMContentLoaded
event mean?
This event is fired when the browser has fully loaded the HTML, and the DOM tree is built, but external resources like pictures <img>
and stylesheets may not yet have loaded.
How do web API responses differ from typical responses sent to a user that is using a browser to make requests?
API responses are typically just data, represented in a way that makes it easy to put to use.
One thing all APIs have in common is…
providing functionality for use by another program.
What is AJAX?
AJAX stands for: Asynchronous JavaScript and XML (Ajax, or AJAX). It is a web development technique in which a web app fetches content from the server by making asynchronous HTTP requests, and uses the new content to update the relevant parts of the page without requiring a full page load.
What is XMLHttpRequest
purpose? Is it synchronous or asynchronous?
We use XMLHttpRequest
(sometimes referred to as XHR) to make HTTP requests from JavaScript. The default behavior is for requests to be asynchronous, but this can be altered when configuring the object using the open()
method.
Tip: Use CSS set display to none to ‘hide’ things rather than delete them from the DOM!
display: none
AJAX is a technique used to exchange data between a browser and a server without…
causing a full page reload.
The load
event on a XMLHttpRequest
object means…
the response has loaded.
The loadstart
event on a XMLHttpRequest
object means…
the request has been sent to the server.
The loadend
event on a XMLHttpRequest
object means…
the response loading is done and all other events have fired. This is the last event to fire.
The word “async” before a function means one simple thing…
The function always returns a Promise.
The await
keyword before a promise makes JavaScript wait until that promise settles, and then…
1) If it’s an error, an exception is generated — same as if throw error were called at that very place.
2) Otherwise, it returns the result.
An HTMLCollection
is always a ____ collection
live