Javascript p2 Flashcards
DOM querying +
What is the DOM?
Document Object Model
- DOM is an API (Application Programming Interface), a UI/means by which programs and scripts talk to each other.
- The DOM states what your script can ask the browser about the current page, and how to tell the browser to update what is being shown.
Why do we log things to the console?
– to get feedback, learn what is where so we can manipulate it
What is a “model”?
– a replication, example, representation
Which “document” is being referred to in the phrase Document Object Model?
– the website in question
What is the word “object” referring to in the phrase Document Object Model?
- the model is made of objects, an object-model of the document
- each object represents a different part of the page loaded in the browser
What is a DOM Tree?
- a model of a web page
- - document nodes, elements nodes, attribute nodes, text nodes
Give two examples of document methods that retrieve a single element from the DOM.
- getElementById(‘id’), uses value of an elements ID attribute, which should be unique on the page
- querySelector(‘css selector’), returns first matching element
Give one example of a document method that retrieves multiple elements from the DOM at once.
- getElementsByClassName(), grabs all elements of a class
- getElementsByTagName(), grabs all elements of a tag name
- querySelectorAll(), grabs all elements of a CSS selector
Why might you want to assign the return value of a DOM query to a variable?
- cache a thing when you need to work with it more than once
- this stores a reference to where the node is, not the element itself but directions to it
What console method allows you to inspect the properties of a DOM element object?
– console.dir()
Why would a script> tag need to be placed at the bottom of the HTML content instead of at the top?
–the browser needs to parse all the elements in the HTML before the JS code can access them
(sneaky:
script js.link defer script
defer will cache the code to run after page loads so link can go in head)
What does document.querySelector() take as its argument and what does it return?
– takes a CSS selector and returns the first matching element
What does document.querySelectorAll() take as its argument and what does it return?
– takes a CSS selector and returns a node list of all elements which use it
node list vs array?
- a NODE LIST is not an ARRAY. it just sort of looks and acts like one
- they are numerically indexed objects that look like arrays
Why do we log things to the console?
– to get feedback, learn what is where so we can manipulate it
What is the purpose of events and event handling?
- to make the site feel more interactive
- - by causing responses to various prompts
Are all possible parameters required to use a JavaScript method or function?
– no. not all methods require all parameters set, some are optional
What method of element objects lets you set up a function to be called when a specific type of event occurs?
– .addEventListener(‘event’, function, optional)
What is a callback function?
– a function we give to another function
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
What object is passed into an event listener callback when the event fires?
– the event object, passed in by the element
callBackFunction(event) { }
What is the event.target? If you weren’t sure, how would you check? Where could you get more information about it?
- the target property will store the element that was interacted with
- console.log()
What is the difference between these two snippets of code?
1) element.addEventListener(‘click’, handleClick)
2) element.addEventListener(‘click’, handleClick())
1) element.addEventListener(‘click’, handleClick)
- - this one would run handleClick when the click event fires
- - a callback function
2) element.addEventListener(‘click’, handleClick())
- - this will pass the return of handleClick() as the argument, not the function itself
- - this one would run handleClick as the page loads, rather then on event fire
What is the className property of element objects?
– the classes assigned to that element
How do you update the CSS class attribute of an element using JavaScript?
– el.className = ‘all class names to apply’
What is the textContent property of element objects?
– allows you to access the text content in the element
How do you update the text within an element using JavaScript?
– el.textContent = ‘new text’ or other variable value
Is the event parameter of an event listener callback always useful?
– not always
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
– more complicated
Why is storing information about a program in variables better than only storing it in the DOM?
– quicker, easier to manipulate
What event is fired when a user places their cursor in a form control?
– focus
What event is fired when a user’s cursor leaves a form control?
– blur
What event is fired as a user changes the value of a form control?
– change
What event is fired when a user clicks the “submit” button within a form?
– submit event
What does the event.preventDefault() method do?
- prevent the browser from automatically reloading the page with the form’s values in the URL.
- prevent refresh of page & submission to URL
What does submitting a form without event.preventDefault() do?
– allows refresh of page and submission to URL
What property of a form element object contains all of the form’s controls?
– HTMLFormElement
– nodeList = HTMLFormElement.elements
The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the element
What property of a form control object gets and sets its value?
– value
What is one risk of writing a lot of code without checking to see if it works so far?
- many errors, no context
- - loss of specificity
What is an advantage of having your console open when writing a JavaScript program?
– immediate feedback
remember there are two kinds of functions:
- ones that return info (void)
- - ones that change things (mutator)
Does the document.createElement() method insert a new element into the page?
– not until you call .appendChild() with it, it only creates the element you can add
How do you add an element as a child to another element?
- node.appendChild(child);
- - will add to end of list
If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).
This means that a node can’t be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent.
- list.insertBefore(child, target); (where target is other child to insert before)
- to add to start of list
What do you pass as the arguments to the element.setAttribute() method?
- the name of the attribute whose value is to be set
- the value to assign to the attribute
- element.setAttribute(attName, value);
What steps do you need to take in order to insert a new element into the page?
- var x = doc.createElement(‘el’) - creates & stores in variable
- var y = doc.createTextNode(‘copy’) - optional, provides content for new element
- x.appendChild(y) - adds content to element
- parent.appendChild(x) - adds element to the page/parent
create: var newEl = document.createElement(‘type to create’);
create: var newText = document.createTextNode(‘text goes here’);
attach: newEl.appendChild(newText);
find loc: var position = document.getElementByTagName(‘tag’)[#];
insert: position.appendChild(newEl);
What is the textContent property of an element object for?
– get or set text content for an element
The textContent property of the Node interface represents the text content of the node and its descendants.
Name two ways to set the class attribute of a DOM element.
- setAttribute();
- - .className =
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
- automate repetitive work
- can be reused
- can change it anytime
What is the event.target?
– the element from which the event originated
The target of the event (most specific element interacted with)
Why is it possible to listen for events on one element that actually happen its descendent elements?
– event bubbling
What DOM element property tells you what type of element it is?
– tagName
What does the element.closest() method take as its argument and what does it return?
– it takes an element name and returns the closest of that element to the calling element
el01.closest(el02) == closest el02 to el01
The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.
How can you remove an element from the DOM?
– element.remove();
The Element.remove() method removes the element from the tree it belongs to.
If you wanted to insert new clickable DOM elements into the page using JavaScript, how could you avoid adding an event listener to every new element individually?
– by adding one to the parent, and using bubbling event to catch it
3 parts of adding an event listener:
- callback function
- var $element = doc.querySelector(‘element’);
- $element.addEventListener(‘event’, callBack);
what’s a Logic Gate?
- a check to exit a function if condition not met
talk about node lists:
nodeLists can be looped through even though they aren’t arrays
NodeList objects are collections of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll().
Although NodeList is not an Array, it is possible to iterate over it with forEach() or a for loop (but not for…in). It can also be converted to a real Array using Array.from().
What is the event.target?
– the element from which the event originated
The target of the event (most specific element interacted with)
// Get the element, add a click listener... document.getElementById("parent-list").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item if(e.target && e.target.nodeName == "LI") {
// List item found! Output the ID! console.log("List item ", e.target.id.replace("post-", ""), " was clicked!"); } });
What is the effect of setting an element to display: none?
– removes the element from the flow of the doc
What does the element.matches() method take as an argument and what does it return?
– it takes a selector string and returns a boolean saying if that string matches the element
The matches() method checks to see if the Element would be selected by the provided selectorString – in other words – checks if the element “is” the selector.
var result = element.matches(‘.selectorString’);
How can you retrieve the value of an element’s attribute?
– with .getAttribute()
The getAttribute() method of the Element interface returns the VALUE of a specified attribute on the element.
let attribute = element.getAttribute(attributeName);
At what steps of the solution would it be helpful to log things to the console?
– any step that assigns or returns values
If you were to add another tab and view to your HTML, but you didn’t use event delegation, how would your JavaScript code be written instead?
– more listeners and callback functions
If you didn’t use a loop to conditionally show or hide the views in the page, how would your JavaScript code be written instead?
– many if/else statements
What is JSON?
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.
What are serialization and deserialization?
– serialization: converting native object into string
– deserialization: converting string to a native object
Converting a string to a native object is called deserialization, while converting a native object to a string so it can be transmitted across the network is called serialization.
Why are serialization and deserialization useful?
– you can pack up objects into a relatively small bundle (of bytes, a bit sequence) to transfer or store them in memory, then unpack them later without any loss
Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications
How do you serialize a data structure into a JSON string using JavaScript?
-- JSON.stringify() The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space)
How do you deserialize a JSON string into a data structure using JavaScript?
–JSON.parse()
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
JSON.parse(text)
JSON.parse(text, reviver)
How to you store data in localStorage?
- .setItem()
- - localStorage.setItem(keyName, keyValue);
How to you retrieve data from localStorage?
- .getitem()
- - var aValue = localStorage.getItem(keyName);
What data type can localStorage save in the browser?
– JSON string data
When does the ‘beforeunload’ event fire on the window object?
– when the window, the document, and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.
What is a method?
A method is a function which is a property of an object. There are two kind of methods: Instance Methods which are built-in tasks performed by an object instance, or Static Methods which are tasks that are called directly on an object constructor.
How can you tell the difference between a method definition and a method call?
- a def will have a codeblock following it, creating what it does
- a call would be: object.method(); (dot notation)
Describe method definition syntax (structure).
person.name = function () {
return this.firstName + “ “ + this.lastName;
};
–
const obj = {
foo() {
// …
},
bar() {
// …
}
}
Describe method call syntax (structure).
- object.method
- - object.method();
How is a method different from any other function?
– it’s a part of an object
What is the defining characteristic of Object-Oriented Programming?
objects can contain both data (as properties) and behavior (as methods)
What are the four “principles” of Object-Oriented Programming?
- abstraction
- encapsulation
- inheritance
- polymorphism
What is “abstraction”?
being able to work with (possibly) complex things in simple ways
What does API stand for?
- application programming interface
- - a connection between computers so they or their programs can interact
What is the purpose of an API?
– to give programmers a way to interact with a system in a simplified, consistent fashion (an abstraction)
What is this in JavaScript?
– a self-referential parameter ?
– a contextual parameter ?
–
A better question to ask is “When is this?”
–
By default, when you call a function, it’s this will be given the value of the global window object.
What does it mean to say that this is an “implicit parameter”?
it means that it (this) is available in a function’s code block even though it was never assigned in the function’s parameter list or declared with var
- which is to say, it is not explicitly defined, but instead implicitly available
- it does not need to be explicitly defined
When is the value of this determined in a function; call time or definition time?
– call time. the value of this is determined when the function is called, not defined.
What does this refer to in the following code snippet? var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
– the value of the firstName property of THIS object, var character
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
- it would return: ‘It’s-a-me, Mario!’
- bc character is the object which contains the method ‘greet’, which refers to the firstName property of character in its codeblock
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
Given the above character object, what is the result of the following code snippet? Why? var hello = character.greet; hello();
- undefined
- it’s being called on the default global scope (the window), not the specific obj
- var hello = character.greet; hello(); - what character? greet() refs 'this' inside the character obj, so it won't work outside in global
How can you tell what the value of this will be for a particular function or method definition?
- no way to know for sure
- - it’ll be referring to the properties of the object it’s within ?
How can you tell what the value of this is for a particular function or method call?
– the dot notation will tell you/it which object it’s referring to
– the lexical scope of the call
–
Find where the function is called and look for an object to the left of the dot. If you can’t see where the function (or method) is called, then you cannot say for sure what the value of this is.
This list is not comprehensive, but if you remember the following rules, you should be able to understand code that utilizes this in simple scenarios:
- this is an implicit parameter of all JavaScript functions.
- the value of this is determined at call time.
- the value of this can be recognized as “the object to the left of the dot” when the function is called (as a method).
- if there is no value to the left of the dot when the function is called, then by default, this will be the global window object.
- if you cannot see the function being called, then you do not know what the value of this will be.
By default, when you call a function, it’s this will be given the value of the global window object.
(answer is example)
function thisIsWindow() { if (this === window) { return 'yep' } else { return 'nope' } }
thisIsWindow(); // “yep”
var pet = { type: 'doggo', rating: 12 };
pet. thisIsWindow = thisIsWindow;
pet. thisIsWindow(); // “nope”
What kind of inheritance does the JavaScript programming language use?
– prototypal, or prototype-based
What is a prototype in JavaScript?
- template from which objects draw their abilities (methods/functions, etc)
- an object which has some functionality that would be applied to any object created out of it
How is it possible to call methods on strings, arrays, and numbers even though those methods don’t actually exist on objects, arrays, and numbers?
- bc they exist on their associated prototype
- -
objec. setPrototypeOf(obj, prototype);
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
– on the prototype