6 DOM & JavaScript

Ace your homework & exams now with Quizwiz!

What does console.log( ) do?

displays informational data to the console

What method of a DOM node creates a copy of another DOM node, but not the node's children?

document.cloneNode(false)

What method for a DOM node creates a copy of the node and the node's children?

document.cloneNode(true)

What method for the document object creates a new DOM node for a specific HTML element?

document.createElement

What method for the document object creates a new DOM node to hold content?

document.createTextNode

What is the root of the DOM tree?

document.documentElement

What are the five primary methods of accessing specific nodes within the DOM?

document.getElementById document.getElementByTheTagName document.getElementByClassName document.querySelectorAll document.querySelector

What are the DOM accessor properties for each node that allow direct navigation to sibling or parent nodes? (3)

nextSibling prevSibling parentNode

List 7 common HTML5 Form Validation and what they do.

required attribute indicates that the field must have a value prior to submitting the form. max and min attributes indicate the max and min value that can be entered in an input field with ranges, such as a date or number. maxlength and minlength attributes indicate the maximum and minimum length of input allowed by an input field. pattern attribute provides a regular expression that valid input must match. title attribute can be used to provide a description of valid input when using the pattern attribute.

The document object is a property of the window object. How can it be accessed?

window.document o just document

What window object property is useful for determining if the web page is loaded using HTTPS or HTTP?

window.location.protocol is "https" or "http", depending on which protocol the URL is suing.

What property returns the browser's language?

window.navigator.language

What window object property likely produces the following output? document.writeIn(window.________); Mozilla/5.0 (WIndows NT 10.0; WOW64) AppleWebKit/537.36 Chrome/53.0.2785.116

window.navigator.userAgent is the browser's user agent, which differs between browsers.

What window method is ideal for displaying a pop-up advertisement?

window.open() opens a new browser that displays HTML.

What is the difference between window.open( ) and window.alert( )?

window.open() opens a new browser that displays HTML. window.alert() can only display a single message, which is not ideal for advertising

What is the syntax to load bootstrap.js from an external file?

. <script src="bootstrap.js"></script

What are 4 pseudo-classes that HTML5 forms provide to help CSS styling of forms?

:valid is active on an element when the element meets all the stated requirements in field attributes. :invalid is active on an element when one or more of the attributes in the field are not fully met. :required pseudo-class is active on element if the element has the required attribute set. :optional pseudo-class is active on an element if the element does not have the required attribute set.

What is a DOMContentLoaded event caused by?

A DOMContentLoaded event is caused when the HTML file has been loaded and parsed, although other related resources such as CSS, JavaScript, and image files may not yet be loaded.

What is a blur event caused by?

A blur event is caused when an element loses focus and the element will no longer receive future keyboard input.

What is a change event caused by?

A change event is caused by an element value being modified. Ex: Selecting an item in a radio button group causes a change event.

What is a focus event caused by?

A focus event is caused when an element becomes the current receiver of keyboard input. Ex: Clicking in an input field causes a focus event.

What is a load event caused by

A load event is caused when the browser completes loading an HTML element, usually the body.

What does the appendChild method do?

A method on a DOM node which turns another DOM node into the first DOM node's last child. The code parent.appendChild(node_to_move) causes node_to_move to become parent's last child.

What is event-driven programming?

A programming style where code runs only in response to various events.

What is a submit event caused by?

A submit event is caused when the user submits a form to the web server.

What is the purpose of the async attribute?

Allows browser to process the web page concurrently with loading and processing the JavaScript

What is the purpose of the defer attribute?

Allows the browser to load the web page concurrently with loading the JavaScript, but the JavaScript is not processed until the web page is completely loaded.

What is an event?

An action usually caused by the user that the web browser responds to

When would an anonymous function used as an event handler be preferred?

An anonymous function does not have a name. Some developers prefer anonymous functions for event handlers over named functions when anonymous functions require writing fewer lines of code.

What is the childNodes property?

An array-like collection of objects for each of the node's children

What is a node in the DOM tree?

An individual object

What is an input element caused by?

An input event is caused when the value of an input or textarea element is changed.

What events do not bubble? What happens when non-bubbling event occurs?

Blur, focus, and change. The browser will follow the event capturing phase, the at target phase, then stop.

What does the stopPropagation() method do?

Called on an event object. Browser stops the traversal process, but still calls relevant registered handlers on the current node.

What does the preventDefault() method do?

Called on event object. Stops the web browser from performing the built-in handler.

What is the mouseover event caused by?

Caused by mouse entering the area defined by an HTML element.

What is the mouseout event caused by?

Caused by mouse exiting the area defined by an HTML element.

What is the mousemove event caused by?

Caused by mouse moving within the area defined by an HTML element.

What is the keypress event caused by?

Caused by the user pressing and releasing a key on the keyboard.

What is the keydown event caused by?

Caused by the user pushing down a key on keyboard.

What is the keyup event caused by?

Caused by the user releasing a key on the keyboard.

What does the createTextNode method do?

Creates a DOM node containing a text specified by a string argument. Must be added to the DOM using appendChild or insertBefore

What does the createElement method do?

Creates a DOM node from a string parameter for an HTML element.

What must be pressed in chrome to view the console?

Ctrl + shift + J for windows or linux. Cmd + Opt + J for mac.

What is the significance of using firstChild?

DOM tree represents textual content separately from the HTML elements. The textual content of an HTML element is the first child node of the HTML element's node. Using firstChild.nodeValue is used to access the value of the HTML's element's first child.

What does console.dir( ) do?

Displays a JavaScript object to the console. The browser usually supports a method for compactly representing the object. Ex: a hierarchical tree representation allowing a developer to expand and collapse the object contents.

What does the window.confirm() method do?

Displays a confirmation dialog b ox with OK and Cancel buttons. Returns true if OK is pressed and false if cancel is pressed.

What does the window.alert() method do?

Displays an alert dialog box.

What does console.error( ) do?

Displays errors to the console. The browser usually has a special indicator to differentiate an error from a warning or the standard log message. A red error box.

What does console.warn( ) do?

Displays warnings to the console. The browser usually has a special indicator to differentiate a warning from the standard log message. A yellow warning box.

What is DOM?

Document Object Model. General way to represent & access all parts of HTML and XML documents.

What is a style object?

Each HTML element has one. Represents the active CSS styling for the element. The style object has separate properties for each CSS rule applied to the element. The name of the style properties are the same as the CSS properties with some minor exceptions.

What are the three ways to write handlers?

Embedding the handler as part of the HTML button. Ex: <button onclick="clickHandler()">Click Me</button> Setting the DOM node event handler property directly using JavaScript. Ex: document.getElementById("myButton").onclick = clickHandler Using JavaScript addEventListener() method to register an event handler for a DOM object. document.getElementById("myButton").addEventListener("click", clickHandler)

List and describe the three phrases of the DOM traversal process

Event capturing phase The browser traverses the DOM tree from the root to the event target node, at each node calling any event-specific handlers that were explicitly registered for activation during capturing phase. Target Phase Browser calls all event-specific handlers registered on the target node. Event Bubbling Phase: Browser traverses the DOM tree from the event target node back to the root node, at each node calling all event-specific handlers registered for the bubbling phase on the current node.

Code that runs in response to an event is called what?

Event handler or event listener

True or False: One script element can be used to include both inline JavaScript and a reference to an external JavaScript file.

False. A script element can either be used for inline JavaScript or an external JavaScript file.

True or False: A web browser will process the HTML following a script element that uses an external JavaScript file while the browser waits for the web server to return the JavaScript file.

False. A web browser will wait for a script element's external file to load before continuing to process the HTML. As a result, many web developers place their scripts at the end of the HTML.

True or False: When writing custom JavaScript, the defer attribute is usually better than the async attribute.

False. Custom JavaScript can take advantage of concurrent processing with HTML. As a result, a developer may see better performance using the async attribute instead of the defer attribute.

True or False: One script element can be used to reference multiple external JavaScript files.

False. Each external JavaScript file must be referenced by separate script elements.

True or False: A blur event occurs when the mouse is moved over another input element.

False. Just moving the mouse causes mousemove and mouseout events, but another element must be actively selected to cause the blur event.

True or False: The DOM only refers to the HTML portions of the document

False. The DOM refers to the styling set by the CSS, the images displayed by the HTML, and any other resources the JavaScript may need to create an interactive experience in the browser.

True or False: The actions a web browser notices are called handlers

False. The actions are called events and the code that executes in response to those events are called handlers.

True or False: The createElement adds the created DOM node to the DOM tree?

False. The createElement method does not add the created DOM node to the DOM tree, so the programmer must use appendChild or insertBefore to add the new node to the existing DOM tree.

True or False: The browser interprets the defer and async attributes for the script element the same.

False. The defer attribute indicates the browser should wait to interpret the JavaScript until the HTML has been processed, while the async attribute indicates the browser can process the HTML and JavaScript concurrently.

True or False: A web developer must implement the code to detect events and calls the appropriate handlers.

False. The web browser hides the code that calls the handlers so a web developer can focus on writing event handlers.

True or False: A web developer cannot prevent the web browser from performing built-in handlers.

False. The web developer can call preventDefault() on an event object to stop the built-in action from occurring.

What are the steps to validating each field as data is entered?

For each field that should be validated, register an input event handler for the field. Create a global variable that tracks whether the field is currently valid. In most cases, this global variable should be false since the form typically starts with the field as invalid. Modify the global variable as appropriate within the field's event handler. Register a submit event handler for the form that verifies the global variables for each field are true. If one or more of the global variables are false, call the preventDefault() method on the event to cancel the form submission and keep the form from being sent to the server.

In the DOM visualization tree, what does the green node represent? What does the pink node represent? What does the blue node represent?

Green nodes represent the HTML elements. Pink nodes represent the HTML attributes. Blue nodes represent the text content of the HTML elements.

What is the purpose of window.innerHeight and window.innerWidth properties?

Height and width in pixels of the window's content area.

What is the document object?

It is a data structure representing the entire web page DOM, including HTML and all other resources included by the web page, like CSS, image, and JavaScript files. Changes made to it will be reflected in the browser presentation and/or behavior

Why is the <meta> tag not included in the DOM tree?

Meta tag is used to describe the contents of the document and is not part of the document contents.

If most browsers support HTML5, can web developers do all form data validation using HTML5 input element attributes and not use JavaScript validation?

No. HTML5 form validation may simplify and automate some validation, but validation requirements not supported by the builtin attributes still require JavaScript. Ex: JavaScript is needed to check if a date corresponds to a specific day of the week.

If validation shows that a form input value is invalid, should the input value be reset to the initial value?

No. Resetting the input by clearing the value is often more annoying than helpful to the users. Ex: Resetting a ZIP code value from "12345-678" to "" because the four-digit extended ZIP code is invalid forces the user to retype the entire ZIP code.

What does the window.open() method do?

Open a new browser window.

What is the purpose of the document.writeIn() method?

Outputs HTML into the document and alters the DOM

What does the parentNode property refer to?

Parent element containing the node.

What is the purpose of minification?

Process of removing unnecessary characters (like whitespace and comments) from JavaScript code so the code executes the same but with fewer characters. Minification software may also rename identifiers into shorter ones to reduce space. Uses ".min.js"

What does the DOM accessor property parentNode do?

Refers to the current node's parent node.

What does the DOM accessor property nextSibling do?

Refers to the node with the same parent following the current node in the document

What does the DOM accessor property prevSibling do?

Refers to the node with the same parent preceding the current node in the document

What three things are needed to validate form data upon submission?

Register a handler for the form's submit event that executes a validation function. Within the validation function, inspect the form's input fields via the appropriate DOM elements and element attributes. If the form is invalid, call the preventDefault() method on the event to cancel the form submission and prevent the form data from being sent to the server.

What does the removeChild method do?

Removes a node from the method's caller's children.

What is the window object do?

Represent an open browser window.

What does the document.getElementsByClassName do?

Return an array containing all the DOM nodes whose class attribute matches the method's parameter

What does the document.querySelectorAll do?

Returns an array containing all the DOM nodes that match the CSS selector passed as the method's parameters.

What does the document.getElementById do?

Returns the DOM node whose id attribute is the same as the method's parameter

What does the document.getElementByTagName do?

Returns the array containing all the DOM nodes whose type is the same as the method's parameter.

What does the document.querySelector do?

Returns the first element found in the DOM that matches the CSS selector passed as the method's parameter.

What does the innerHTML property do? Why is it important?

Sets or gets a DOM node's content, including all of the node's children, as a string instead of as a tree. Allows web developers to invoke multiple changes to the DOM in one line of code.

What does the nodeValue property do?

Sets or gets the value of text nodes.

What is the purpose of a JavaScript obfuscator?

Software that converts JavaScript into an unreadable form that is very difficult to convert back into readable JavaScript. It is to prevent the code from being read or re-purposed by others. Uses ".min.js"

What does the removeAttribute method do?

Takes a name of an attribute as a parameter. It removes the corresponding attribute from the node.

What is the difference between the children property for a node and the childNodes property?

The childNodes property is an array-like object that contains the HTML elements and textual content directly contained within that node. The children property is like the childNodes property except it removes the whitespace-only textual nodes from the childNodes collection.

What does the clearInterval() method do?

The clearInterval() method takes one argument: a unique identifier for an interval that has been created. After a call to clearInterval(), no further calls to the associated handler will be made.

What doe s the clearTimeout() method do?

The clearTimeout() method takes one argument: a unique identifier for a timeout that has been created. If the timeout has not yet occurred, clearTimeout() turns off the associated timer. Otherwise, clearTimeout() doesn't do anything. Ex: clearTimeout(uid); stops the timer and causes the timeout event associated with the uid unique identifier to not occur.

What does a modern browser provide that allows the JavaScript code to produce information and debugging output for the web developer?

The console, which does not affect the functionality or presentation of the web page. By default, the console is not open for viewing on a page.

What doe the setInterval() method do?

The setInterval() method takes two arguments: a recurring timeout in milliseconds (t), and a handler. The browser calls the handler every t milliseconds until the recurring timeout has been canceled. A recurring timeout is also called an interval. The setInterval() method returns a unique integer identifier that refers to the recurring timeout that was created.

What does setTimeout() do?

The setTimeout() method takes two arguments: an event handler, and a time delay in milliseconds (1/1000th of a second) until the timeout occurs. The browser calls the handler after the timeout has occurred. The setTimeout() method returns a unique integer identifier that refers to the timeout that was created. Ex: var uid = setTimeout(function() { alert("Hello!"); }, 2500); causes a timeout event to occur after about 2.5 seconds.

True or False: The following two JavaScript fragments are functionally equivalent. setTimeout(function() { alert("Hello!"); }, 2500); function hello() { alert("Hello!"); } setTimeout(hello, 2500);

The setTimeout() or setInterval() handlers accept either a complete function definition (anonymous function) or just the name of a function to execute when the timeout event occurs.

True or False: In a tabbed browser, each tab has a windwo object.

True

True or False: Every handler has an optional event object parameter that provides details of the event.

True

True or False: Most web pages on the internet were written before the defer or async attributes were standardized.

True Many web pages do not use asynchronous or deferred execution of JavaScript. The load speed of these web pages could be improved by using the async and defer attributes

True or False: setInterval() and setTimeout() both return identifiers for their associated handlers.

True.

True or False: When using a third-party JavaScript library, the defer attribute is usually better than the async attribute.

True. A third-party JavaScript library may assume that the DOM is already loaded. Thus, the defer attribute ensures the DOM is loaded before the JavaScript. However, a well writtel library will not make assumptions about the DOM availability.

True or False: A mouse click causes an event.

True. A web page may need to change functionality based on when and where the mouse is clicked, so mouse click events are detected by the browser. A web developer can write a handler that implements the desired behavior in the web page when the event occurs.

True or False: If a web developer creates a "default" handler for a DOM node high in the tree and a more specific handler for a DOM node lower in the tree, the web browser will run both handlers for an event.

True. By default, the web browser will call both handlers. stopPropagation() can be called in the more specific handler to keep the browser from continuing the bubbling process. If stopPropagation() is called, the web browser will not call handlers higher in the DOM tree.

True or False: Every attribute for an HTML element has an identically named property in the element's DOM node

True. Ex. <a href="http://www.nasa.gov/" id ="nasa_link">NASA</a> has a correpsonding DOM node with properties name href and id. Each attribute property acts as both a getter and a setter.

True or False: The DOM is accessible via the global object named document.

True. For ease of access, the DOM is available in any JavaScript code from the document object.

True or False: Window object properties or methods can be accessed without putting window. in front of the property or method.

True. JavaScript properties and methods do not have an explicit named object associated with the window object by default. Ex. window.alert("test") and alert("test") are equivalent.

True or False: document.writeIn("<div>test</div>") adds a div element to the DOM

True. Output from document.writeIn() alters the DOM.

True or False: Bubbling is the preferred process for the web browser to find appropriate handlers for an event.

True. The bubbling process matches other graphical event systems and is easier to use.Only use the capturing process for very specific cases.

True or False: Since clearInterval() and clearTimeout() take an identifier as a parameter, the methods can be used interchangeably.

True. The names are unique to help the reader, but the methods must use the same underlying structure according to the W3C specification. Good practice is using the name that is most clear, thus reducing potential confusion.

True or False: The web browser performs the event capturing process before the bubbling process.

True. The web browser traverses the DOM tree from the root to the node where the event occurs (capturing), and then traverses the DOM tree back to the root following the same path but in the reverse direction (bubbling).

If all the fields in a form have been validated before submitting the form data to a server, does the server need to repeat the field validation?

Yes. A web server should never trust that incoming data is valid. A knowledgeable and determined user can entirely bypass all browser validation.

Is validating input fields as the user fills in each field better than validating the entire form after all the form data has been entered?

Yes. Best practice is to give the user feedback about problems as soon as possible unless a compelling reason exists to do otherwise.

What does the insertBefore method do?

a method on a DOM node which moves one DOM node to be a previous sibling to another DOM node. The code parent.insertBefore(existing, node_to_move) causes node_to_move to be a child of parent immediately preceeding existing.

How does the addEventListener method know whether the handler is registered for what phase?

addEventListener has an optional third parameter that indicates whether the handler is registered for the capturing phase or bubbling phase. If the third parameter is false or not specified, the browser registers the handler for the event bubbling phase. If the parameter is true, the browser registers the handler for the capturing phase.

What are three methods for changing node locations within the DOM?

appendChild insertBefore removeChild

What is the click event caused by?

caused by a mouse click

What method duplicates existing nodes in the DOM? How does it work?

cloneNode creates a DOM node or tree identical to the tree rooted at the method's caller. The method's boolean argument indicates whether the method should clone the node's children. Ex: x.cloneNode(true) creates an identical tree as that rooted at x, and x.cloneNode(false) creates a single node identical to x. The created tree or node must be added to the DOM using appendChild or insertBefore

What console method is best to display a structured JavaScript object?

console.dir( )

What console method is best for reporting unexpected problems.

console.error( ) Can be called to display the state of the code for debugging. A well written error message can be used by the developer to reproduce the problem and fix the bug.

What console method is best to help determine why an algorithm isn't working as expected?

console.log( ) It is useful for printing debugging messages that help the programmer. console.log is also helpful for seeing simplified visualizations of JavaScript data or parts of the DOM.

What console method is best for checking that assumptions in an algorithm are correct?

console.warn() It can be placed in strategic places in the code to indicate when those assumptions are not true.


Related study sets

RN Maternal Newborn Online Practice 2019 A

View Set

#8 Reading Assignment Test "The Ground On Which I Stand"

View Set

Marketing Exam 4: Ch. 14, 15, 16, 17

View Set

Microeconomics Econ 101 Chapter 9: International Trade Notes

View Set

Chapter 11: Families and Intimate Relationships

View Set