JavaScript DOM Flashcards

1
Q

If you use parseInt on the value “345ss”, what will you get?

A

345 - it will ignore the string in it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

If you use parseInt on the value “345s4s”, what will you get?

A

345 - it will stop at the first non numerical character

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

If you use parseInt on the value “s345ss”, what will you get?

A

NaN - it will determine that the value is not a number because the first character is a char.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What month would be printed out with the following declaration?

var someDate = new Date(2015, 9, 22, 9);

A

October - months are 0 indexed… for some reason…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

the Date object has some useful methods, what would you use to extract the full year?

A

dateObject.getFullYear()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

If the month is set to 0 (jan), and you call someDate.setDate(32); - what is the result?

A

It will give you Feb, 1st. The system is smart enough to wrap the value around.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What’s an alternative to using Number on a string to convert it?

A

Subtract 0. This will coerce the string to a number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why would you populate the JS Date object from serverside data, rather than relying on the JavaScript Date object?

A

Because you can’t be sure the client side computer is set up correctly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Given the following code, what will be printed out?

var myarray = [1, 2, 3, 4, 5, 6, 7];

console.log(myarray.slice(1, 4));

A

2, 3, 4

NOTE: the indexes are zero based. And in the slice function, the first parameter is inclusive, the second is not

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

var myarray = [1, 2, 3, 4, 5, 6, 7];

console.log(myarray.slice(3));

A

4, 5, 6, 7

With only one parameter is selects and returns the array starting from the parameter (remember it’s inclusive, so it will start from the fourth postion - 0, 1, 2, 3 - which here contains 4) - and give you the remaining part of the string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a significant use of the array’s join and split functions?

A

When using an array - it’s obviously useful to be able to iterate over it. However sending it over the wire we may want to send it as a string. We can use join and split to convert to / from a string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Is the sort method of the array object destructive?

A

Yes - it will modify the original array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you compare two string objects using the == operator?

A

string1.valueOf() == string2.valueOf();

Without this we would be comparing two string objects which would return false as they are indeed different objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

In a traditional web application, where does the business logic live?

A

On the server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

In a traditional web application, where does the content layer live?

A

On the server

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is one reason to not embed javascript into the script tags of a HTML page?

A

Because a script error could prevent the page from loading.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the security reason to keep JS in separate files?

A

The CSP - content security policy will make sure only the code being run from separate files will be run.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What variable holds the browser name / version?

A

navigator. appName

navigator. appVersion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Browser sniffing is a bad way to determine funtionality - what is the recommended way?

A

Object detection

if (functionalityIwant) {
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What can you use to determine whether the browser supports the currently recommended W3C DOM level?

A
if (document.getElementById) {
   // It's a modern browser
}

If you need to test for older IE browsers - you can use document.all

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What are the layers involved in “progressive enhancement”

A
  1. Semantically valid HTML
  2. CSS
  3. JavaScript - starts when document is loaded
  4. JavaScript - check that W3C DOM is available
  5. JavaScript - Check that desired components are avail.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are some key things to think about with regards to JavaScript and accessibility?

A
  1. All content should be available with/without JS
  2. If there is content or functionality that only makes with JS, then the elements must be created by JS (i.e. no hanging buttons).
  3. JS functionality should be independent of user input
  4. If you make non interactive elements into interactive elements, there should be a fall back
  5. Scripts should not redirect, or submit without user interaction
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the shortcomings of using document.write?

A

It only inserts a string - and not a set of nodes / attributes. It’s also difficult to use in separate files as the document only works where you put it into the HTML.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Can you retrieve elements with different class names using getElementsByClassName?

A

Yes - you just pass multiple class names to the function.

var elements = document.getElementsByClassName(“foo bar”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What event can be used to load content after the document is fully loaded?

A

DOMContentLoaded

document.addEventListener(“DOMContentLoaded”, funcName, false);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How can you use array index notation to access the first element in a group of tags?

A

var myElement = document.getElementsByTagName(‘p’)[0];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How could you reach the last element in an array returned by getElementsByClassName?

A
var elements = document.getElementsByClassName('foobar');
element = elements[elements.length - 1];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What does the property nodeType (on an element) tell us?

A

What kind of node it is, based on a number:

Node.ELEMENT_NODE == 1 (an element, like p, li)
Node.TEXT_NODE == 3 (actual text of an element or attr)
Node.PROCESSING_INSTRUCTION_NODE == 7 (header stuff)
Node.COMMENT_NODE == 8 (comments)
Node.DOCUMENT_TYPE_NODE = 10

And there are others. 1 and 3 are used frequently

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What does the nodeName property provide us?

A

The actual name of the node, i.e. h2 - or #text if it is a text node.

NOTE: It’s worth making lowercase - as it sometimes comes out as uppercase.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What does the property nodeValue provide us?

A

If it’s on an element - it will be null, if it is a text node, then it will be the content of the node.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Can the nodeValue of text nodes be read and set?

A

Yes - you can - just be careful when getting the node, that you aren’t trying to set the actual node’s value - rather than it’s child. i.e.

document.getElementsByTagName(‘p’)[0].nodeValue = “Chicken”;

This wont work - although it wont throw an error - because you are trying to set the text of what is actually an element, not the text node OF that element.

document.getElementsByTagName(‘p’)[0].firstChild.nodeValue = “Chicken”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What property contains the list of children nodes for an element?

A

childNodes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is important to realise about childNodes property?

A

It only contains the first level children. It does not cascade down.

You can also access a child element of the current element via the array notation, or the item() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

The properties yourElement.firstChild / lastChild are simply what??

A

Short cuts that are the same as:

yourElement.childNodes[0] and
yourElement.childNodes[yourElement.childNodes.length - 1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

How can you determine whether a node has child nodes?

A

The function hasChildNodes() - which returns a boolean value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Line breaks can sometimes show up as..

A

text - they look like text nodes, but are not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How do you get access to an elements parent node?

A

Use the parentNode property.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How could you test to see if an element is within a parent element with the class “dynamic”

A
var myLinkedItem = document.getElementById('linkedItem');
var parentElem = myLinkedItem.parentNode;

while (!parentElem.className != ‘dynamic’ && parentElem != document.body) {
parentElem = parentElem.parentNode;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What methods are used to check sibling elements?

A
var myLink = document.getElementById('foobar');
var next = myLink.nextSibling;
var prev = myLink.previousSibling;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Given code like this to get a span:

var errorContainer = dateField.parentNode.getElementsByTagName(“span”)[0];

You may try to write to the textNode within it by using “nodeValue”:

errorContainer.firstChild.nodeValue =errorMessage;

What is a possible problem if your text is not appearing?

A

The span in the HTML has no space - if there is no space, then the firstChild will not be a text node (i.e. there is no first child).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

When the setting of the property nodeValue is null - what effect does setting it have?

A

None.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

When should you use innerHTML to set text?

A

Use innerHTML if you are setting text within a HTML tag, (like a paragraph, tag, span etc). (However, createTextNode is probably more correct, as innerHTML has a problem with characters that could be code - and can lead to XSS issues).

Otherwise use appendChild if you are trying add a new DOM element inside of another DOM element.

appendChild is less computationally expensive, as innerHTML does string concatenation, whereas appendChild works directly with the DOM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Can you link getElement calls together to narrow down the search?

A

Yes - you can use the approach like this to just get the links within a div named ‘nav’.

var link = document.getElementById(‘nav’).getElementsByTagName(‘a’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

All HTML attributes defined in the standard can be accessed via properties - why might some be read only?

A

Security reasons.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

How might you change the alt tag on an image using the properties of the element?

(assume it’s the first image with a div element with the id ‘nav’)

A

var image = document.getElementById(‘nav’).getElementsByTagName(‘img’)[0];

image.alt = “changed!”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Some HTML attribute properties have the same name as reserved words in JavaScript - (i.e. for, and class) - how do you deal with this?

A

You use the approved names for JavaScript / DOM.

for might be htmlFor
and class is className
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Instead of using properties, you can change the elements attributes using DOM functions - what are they?

A

getAttribute(‘attr’);

setAttribute(‘attr’, value);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What does document.createElement(‘a’) do?

A

Creates a new element of type a - a link.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What does document.createTextNode(‘string’) do?

A

Creates a new text node that contains the string, ‘string’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What does node.appendChild(newnode); do?

A

Creates a new node that is added as a child to a node, and following any existing nodes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What does newNode = node.cloneNode(true); do?

A

Clones a node - if the parameter is true, it clones any child nodes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What does node.insertBefore(newNode, oldNode); do?

A

inserts newNode as a child of node and before oldNode

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What does node.removeChild(oldNode); do?

A

Removes the child oldNode from node

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What does node.replaceChild(newNode, oldNode); do

A

Replaces the childNode, oldNode of node;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

What does node.value do?

A

Returns the current value of the node;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

Is script or not script tags valid in the body of the HTML?

A

No - it’s not semmantically correct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Rather than using no-script, (which is now deprecated) - how do you tell your users that there is a problem with JS?

A

Use a div / p with a “no-script” id. If the scripting is available, then it will remove that content and replace it with the desired content.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

Does the create (createElement etc) functions actually add an element to the page?

A

No - it just creates an element ready for insertion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Normally you would find the outer element, then use replaceChild to remove it - what if you only know the ID for the actual element you want to replace - how would you access it?

A

You would find the element, step up a level, then replace it.

var noJSmsg = document.getElementFromId('no-script');
noJSmsg.parentNode.replaceChild(linkPara, noJSmsg);

NOTE: We use parentNode to get to the containing element, then we use replaceChild to replace the DOM element that we are actually calling this from (noJSmsg).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

The meta charset declaration should be…

A

before any elements that contain text.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What are the most common node types?

A
DOCUMENT_NODE
ELEMENT_NODE
ATTRIBUTE_NODE
TEXT_NODE
DOCUMENT_FRAGMENT_NODE
DOCUMENT_TYPE_NODE
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

If you were interested in seeing the numerical values of the node types - how could you do it?

A

You can use the Node object - Node.ELEMENT_NODE.

These are basically constants / enums.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

What is the risk with using Node properties and methods on attributes?

A

The ATTRIBUTE_NODE is being deprecated in DOM4. Attr used to inherit from Node in DOM1, 2 and 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

Do all node types inherit from Node?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

What is the alternative to using getElementById, getElementsByClass etc?

A

querySelector()

It’s very useful because you can pass more complex css style query selectors. However, it’s support is less extensive than the standard functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

What value is TEXT_NODE?

A

3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

What value is DOCUMENT_NODE?

A

9

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

What value is DOCUMENT_TYPE_NODE?

A

10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

What value is ELEMENT_NODE?

A

1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

What value is DOCUMENT_FRAGMENT_VALUE?

A

11

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

When you are looking for the text value of an anchor element (using the property nodeValue) - is the value on the element itself, or the firstChild?

A

the firstChild - since their are typically only null values on elements - the actual value is stored on the text node that is a child of the A element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

Why should createAttribute no longer be used?

A

It’s deprecated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

What is the replacement for createAttribute?

A

getAttribute
setAttribute
removeAttribute

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

What function can be used to create comment nodes?

A

createComment

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

What property of an element can you use to replace the element type?

A

outerHTML

node.outerHTML = ‘ ‘;

NOTE: I didn’t use actual html because of how this editor sucks. But if you node was a span in the HTML, you could specify a full div in those quotes and it would replace the existing span.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

innerText and textContent appear to do the same thing - what’s the differences?

A

Both methods take the text out of the HTML for an element. If there are spans and other html within this block of text it’s removed.

However - innerText formats it a lot like a pre block - i.e. it looks good in a text editor. Text Content preserves some of the spacing and room around the elements that were in their originally.

However - innerText is NOT a standard method - and is not available in Firefox for instance. Do not treat these as equivalent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

What does the insertAdjacentHTML function do?

A

It only works on elements nodes - but it’s quite a precise way of injecting HTML into a page.

node.insertAdjacentHTML(‘beforebegin’, ‘html’);

NOTE: HTML would actually be an element node (not text) - just can’t do it because of this fucking editor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

What are the four positions that insertAdjacentHTML provides?

A

beforebegin
afterbegin
beforeend
afterend

NOTE: Beforebegin and afterend only works if the node is in a tree and has an element parent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

What is the major difference between the textContent property and the insertAdjacentHTML function?

A

The textContent property can only be used for text. If you try to insert HTML via this - it will just insert it as text. i.e. textContent can only be used to create textNodes.

Whereas insertAdjacentHTML is used to create element nodes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

Does document.write stall/pause the page parsing during load?

A

Yes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

Why should you use innerHTML / outerHTML sparingly?

A

They invoke a rather heavy HTML parser

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

Support for outerHTML is not available in Firefox until version 11 - how do you fix this if you need to support earlier versions?

A

There is a polyfill available.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

With regards to hidden elements (i.e. through CSS) - what is the difference between innerText and textContent?

A

textContent is not aware of styles and will return hidden text - whereas innerText will not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

Related to insertAdjacentHTML is the functions insertAdjacentElement and insertAdjacentText, what are the problems with these functions?

A

They are not available in firefox at all.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

What is the difference between innerText and outerText?

A

Both are non-standard functions - however, outerText not only changes the text within the tag, but it also changes the tag. So if you just pass a string into what was a paragraph, the p tags and the content will be replaced with the string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

insertBefore requires two parameters, what happens if you don’t pass the second parameter?

A

It behaves exactly like appendChild

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

Why is removing a node (i.e. removeChild) a multistep process?

A

You have to first select the node that you want to remove, then you have to select it’s parent, then you perform the remove from the parent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

How is removeChild and replaceChild similar?

A

You must do it in a multistep process. Select the node, select the parent, and from there - replaceChild (or removeChild).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

When you use a function like getElementsByTagName, what is returned?

A

A NodeList

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

What is the difference between a NodeList and an array?

A

A NodeList doesn’t have all the benefits of an array - it’s Array like - but not an array. To treat it like an array, you must convert it to an array first.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

How do you convert a NodeList to an array?

A

There are a number of ways. If you don’t care about IE 8..

var childNodeArray = Array.prototype.slice.call(myChildNodes);

Otherwise, simply push the node element onto a new array.

var myNodeList = document.querySelectorAll('div');
var myArray = []; // empty Array
for (var i = 0; i
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

Why does calling appendChild in a loop with a NodeList fail?

A

The NodeList is a live list of DOM elements. If you call append child, the element is moved into the list and removed from the NodeList - thereby shrinking the value of NodeList.length while the loop is running. This causes undefined behavior.

The best thing to do is convert the nodes into an array - and then in a separate loop pass each element individually into appendChild method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

What does calling slice on an array, with no parameters do?

A

It just copies the array - technically, you should pass the first parameter though (I think the ECMA script standard requires it). This is useful for backing up an array that may be modified by other code.

var array = Array.prototype.splice.call(myArray, 0);

var array = myArray.splice(0);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

What is a big difference between slice and splice?

A

slice does not mutate the array - however, splice does.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

When you clone a node using cloneNode - what events are copied across?

A

Any inline events - anything that was attached by using ‘addEventListener’, or node.onClick, will not be copied.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

What is the risk with using cloneNode?

A

You may get duplicate ID’s in the document.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

When you select a group of nodes from the DOM tree - they can be one of two types - what are they?

A

NodeList

HTMLCollection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

A collection can either be…

A

live or static

i.e. live means it’s still part of the actual document, static means its just a snapshot

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

What property exists on a collection that allows you to determine how many nodes are within it?

A

.length

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

What version of ECMAScript was []. implemented in?

A

5

So don’t expect this to work on pre-IE9 browsers. You are better off using Array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
101
Q

When using .childNodes - what do you have to be aware of regarding the nodes being returned?

A

They aren’t going to be just element nodes. It will contain comment and text nodes as well.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

What variable can you use to get a HTMLCollection of all the links on the document?

A

document.links

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
Q

What version of ECMAScript was Array.isArray found in?

A

5

So again - you can’t go using this on pre IE9 browsers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

What is the benefit of converting a NodeList to an array?

A

Once it’s an array, it’s no longer a part of the DOM - which means you wont be affected by or affect the DOM directly.

Also - it provides all of the methods of a true array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

Currently we have to use slice to convert an array like object to an actual array. What is the ECMAScript 6 variant?

A

Array.from

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
Q

What are the properties we can use to traverse the DOM?

A
parentNode
firstChild
lastChild
nextSibling
previousSibling
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
107
Q

Using the properties firstChild etc, it includes things like text nodes and comments. How can you get around this?

A

You can use the following properties:

firstElementChild
lastElementChild
nextElementChild
previousElementChild
children
parentElement

NOTE: Much of these will not work on IE8 or lower - so you might have to use polyfils to replicate the functionality.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
108
Q

How do you determine if a node is contained within another node?

A

document.getElementsByTagName(‘ul’)[0].contains(node);

NOTE: It returns true only if the node passed and the node selected are identical.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
109
Q

You can compare the document position of two nodes, using the compareDocumentPosition() function. What are the return results it gives?

A

0 - Elements are identitical
1 - node and passed in node not in same document
2 - set when passed-in node precedes selected node
4 - set when passed-in node follows selected node
8 - set when passed-in node is ancestor of selected node
16 - set when passed-in node is descendant of selected node (note: - 10 in hex)

NOTE: This can be confusing because a node can have multiple relations - i.e. a node can be both 16 and 4 - and the actual returned value will be 20

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
110
Q

Two nodes are equal, if and only if…

A

The two nodes are the same type
nodeName, localName, namespaceURI, prefix and nodeValue are exactly the same
attributes NamedNodeMaps are identical
The childNodes NodeLists are identical

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
111
Q

How do you compare two nodes?

A

You can use the method isEqualNode

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
112
Q

What’s one gotcha of using the livepreview of brackets when testing for perfect equality of two nodes (i.e. using isEqualNode)?

A

The live preview feature appears to embed values into the elements - (id’s) - and this makes them not equal, when they would have otherwise been.

113
Q

If you don’t care about perfect equality between two nodes - i.e. you just want to know if the two references point to the same node, what do you use?

A

Just use the equality operator === i.e.

document.body === document.body

114
Q

What constructor is used to create the document node?

A

HTMLDocument()

115
Q

How would you get the referrer of a document?

A

document.referrer

116
Q

How would you get the title of a document

A

document.title

117
Q

How would you get the current compatibility mode?

A

document.compatMode

Returns either CSS1Compat (strict mode) - or BackCompat (quirks mode)

118
Q

What nodes are typically returned from document.childNodes?

A

one doctype node

one element node (the HTML element for the document)

119
Q

Is the window.document the same as the Document object?

A

No - the window.document is created using the HTMLDocument constructor - and not the Document object.

120
Q

windows.document provides shortcuts to a few elements, what are some of them?

A

document. title // The page title
document. doctype // The document type
document. documentElement // the html element (contains the language attribute if present)
document. head // the head
document. body // the body

121
Q

How can we determine what type of DOM level a browser supports?

A

if (document.implementation.hasFeature(‘Core’, ‘3.0’);

122
Q

What are the options you can check for in implementation.hasFeature?

A
Core (DOM level)
XML
HTML
Views
StyleSheets etc. etc. 

And many others. Look up documentation on hasFeature to determine the values to expect.

123
Q

hasFeature is useful, but can you trust it alone?

A

No - you must really use capability detection along with it.

124
Q

How do you set an element to be ‘focused’?

A

document.querySelector(‘textarea’).focus();

125
Q

How do you get a reference to the currently selected element?

A

document.activeElement

126
Q

How can you determine if the current page has focus?

A

document.hasFocus()

127
Q

The document.defaultView property is a shortcut to what?

A

The head or global object. In a web browser, that’s window - in a javascript browser environment, defaultView will point to this.

128
Q

If you are dealing with an environment that is headless - or not running in a web browser, you probably don’t have access to the global object “window”. How can you get access to the global scope?

A

Use document.defaultView

129
Q

Each element in a HTML document has a unique behavior - therefore they require unique…

A

JavaScript constructors.

130
Q

What’s one way to determine the constructor that was used on an element?

A

document.querySelector(‘a’).constructor;

131
Q

All of the constructors for HTML elements (HTML*Element) - of which there are many, inherit from what objects?

A

HTMLElement, Element, Node and Object

132
Q

What does Object.keys() do?

A

Returns the enumerable properties (in an array) on the given object.

133
Q

The function createElement creates a new DOM element, can you pass it mixed case names for the elements?

A

Yes - but they are all smashed to lowercase anyway before the element is created.

134
Q

You can use nodeName to get the name of a node - what other method can be used?

A

tagName

135
Q

What is the difference between tagName and nodeName?

A

tagName is meant for retrieving the name of an element - an only an element.

NOTE: Like nodeName, this will be uppercase, regardless of how the document is written.

136
Q

If you have a comment node named ‘comment’ - is this code valid?

comment.tagName?

A

Yes - but it will return undefined. Since tagName does not exist on the comment node. However, you can use nodeName to get the same result.

137
Q

How can you get the attributes of an element?

A

document.querySelector(‘a’).attributes;

138
Q

What does .attributes return?

A

A NamedNodeMap - it’s live, very much like a NodeList - so changing it will change the values of the attributes.

139
Q

If you had an array of attributes - how would you change the value of the href in the live document?

A

Assuming you are using an array straight from the attributes property (i.e. it’s live):

atts[‘href’].nodeValue = ‘http://www.cainmartin.net’;

However - you should use setNamedItem

140
Q

NamedNodeMap has a number of methods that are useful for adding / removing attributes - what are they?

A

getNamedItem()
setNamedItem()
removeNamedItem()

NOTE: It’s probably preferable to use getAttribute, setAttribute, hasAttribute and removeAttribute directly from the node itself.

141
Q

What method can be used to determine if a node has an attribute?

A

.hasAttribute()

142
Q

Should you use removeAttribute, or setAttribute(‘’);

A

Always use removeAttribute.

This also goes for setting the attributes nodeValue to null (don’t do it).

143
Q

What is the best way to make sure an element has a specific attribute?

A

use the hasAttribute method.

144
Q

if you have an attribute - but it’s value is not set - what will hasAttribute return?

A

true

This is because there are some attributes (such as the ‘checked’ attribute that are boolean attributes). The fact that they are there is all that’s required to make them useful.

145
Q

There are two ways to get the list of classes from a node element - what are they?

A

className

classList

146
Q

What is the problem with className?

A

It provides a space separated list that you have to process to get the classnames.

147
Q

What is the problem with classList?

A

Only supported from IE10 upwards - not perfect support.

148
Q

What kind of list does classList return?

A

DOMTokenList

149
Q

Is classList an array or arraylike object?

A

It’s an array like object.

150
Q

Using classList how do you add, or remove a class?

A

classList.add(‘classname’);

classList.remove(‘classname’);

151
Q

Using className, how do you add / remove classes?

A

You have to create a function that uses a regex to remove the string - then reassign the string to the className property. Something like:

function removeClass(e,c) {e.className = e.className.replace( new RegExp(‘(?:^|\s)’+c+’(?!\S)’) ,’’);}

152
Q

Given a class list of “brown big bear” - what method of classList could you use to determine if a specific class exists in that list?

A

var elm = document.querySelector(‘div’);

elm.classList.contains(‘brown’)

153
Q

If you save data on a HTML element, like such:

elm.dataset.gooGoo = ‘goo’;

What does the actual element look like in HTML?

A

goo-goo=”goo”

NOTE: The camel casing is changed to hyphens. This goes for reading the data too.

154
Q

How do you read the data from an element?

A

elm.dataset.gooGoo

Where gooGoo is an attribute named “data-goo-goo” on the element.

155
Q

Because dataset is not available in IE9 (there is a polyfil though) - what can you use instead?

A

getAttribute(‘data-foo’);
setAttribute(‘data-foo’);
hasAttribute(‘data-foo’);
removeAttribute(‘data-foo’);

156
Q

How do you delete a data attribute using data-set?

A

delete dataset.fooFoo

157
Q

Why is querySelector better than getElementById?

A

querySelector has a more robust selection mechanism and can use CSS selectors.

158
Q

Why is querySelector worse than getElementById?

A

It’s not supported as widely (IE8 and above - although IE8 only has CSS 2.1 support).

159
Q

What are the most common methods of selecting a DOM element?

A

document. querySelector(‘a’);

document. getElementById(‘myid’);

160
Q

What is the most common method of selecting a list of nodes in a document?

A

document. querySelectorAll()
document. getElementsByTagName()
document. getElementsByClassName()

161
Q

What is the main difference in the return value from querySelectorAll - and getElementsByTagName?

A

They both return NodeLists - however, querySelectorAll does not return a live list - it’s static, and changing it doesn’t change the content in the dom.

162
Q

querySelectorAll, getElementsByTagName, getElementsByClassName are all defined on individual element nodes - what does this imply?

A

You can limit the query by calling the function only on that node. i.e.

var ulNode = document.querySelector('ul');
var liNodes = ulNode.querySelectorAll('li');
163
Q

What does getElementsByName do?

A

It allows you to select elements that make use of the name attribute.

form, img, frame, embed, object elements all use name.

164
Q

What is the difference between a NodeList and a HTMLCollection?

A

NodeLists and HTMLCollections are both (usually) live collections of nodes, that are array-like in nature. They have all the same methods, with HTMLCollections having the additional property, ‘namedItem’.

Additionally, NodeLists can hold any type of node, whereas HTMLCollections historically could only hold HTML elements, (this may change with DOM4).

165
Q

What is the difference between the properties, children and childNodes?

A

.children is a property of Element. .childNodes is a property of Node. .childNodes can hold any nodes, whereas .children can only hold elements.

i.e.

var el = document.createElement(“div”);

el. textContent = “foo”
el. childNodes.length === 1; // TextNode is a node child
el. children.length === 0; // no Element children

166
Q

HTMLCollections contain elements in what order?

A

Document order, i.e. the order they appear in the document.

167
Q

What are some of the preconfigured legacy arrays that are available from the document root?

A

document. all
document. forms
document. images
document. links
document. scripts
document. stylesheets

168
Q

What datatype are most of the preconfigured legacy arrays (i.e. document.links)?

A

HTMLCollection interface / objects

169
Q

What datatype is the document.stylesheets preconfigured array?

A

StyleSheetList

170
Q

What is something to keep in mind about doucment.all?

A

A) it’s not constructed from a HTMLCollection, it is constructed from a HTMLAllCollection

B) it’s not supported in firefox.

171
Q

Is there a way to determine whether a given element will match a specific CSS selector?

A

Yes, you can use the matchesSelector method

document.querySelector(‘li’).matchesSelector(‘li:first-child’);

BUT NOTE: This doesn’t work in modern browsers - you must use the prefixes (moz, webkit, o, ms - etc).

i.e. mozMatchesSelector.

This would be a good candidate for using a facade pattern to hide this issue.

This method will also be renamed ‘matches’ in later versions.

172
Q

What is the CSSOM View Module?

A

An API that allows the modification of the visual representation within the browser of the DOM.

173
Q

The value of offsetLeft is measured from where?

A

It’s offsetParent. This is usually the nearest ancestor with a position that’s not static - if that can’t be found, then it’s the body (or a TD, TH or TABLE with a CSS position of static).

The value is taken from the top left outer corner of the element to the inner top left corner of the offsetParent.

174
Q

What methods can be used to get the elements top, right, and left border edge offsets relative to the viewport?

A

getBoundingClientRect().

NOTE: The top and bottom edges are measured from the outside border edge of an element to the top edge of the viewport.

175
Q

If you have settigs on a div of:

height: 25px
padding: 25px
border: 25px
margin: 25px

What is the value of offsetHeight and offsetWidth for this div?

A

125px and 125px

Remember margin is not part of the dimensions of the element.

25px border + 25px padding + 25px content + 25px padding + 25px border

176
Q

offsetHeight and offsetWidth include the width of the borders - how would you get this value without the border widths?

A

Use clientHeight and clientWidth

177
Q

If you have settigs on a div of:

height: 25px
padding: 25px
border: 25px
margin: 25px

What is the value of clientHeight and clientWidth for this div?

A

75px 75px

25px padding + 25px content + 25px padding

(borders are not included, nor are margins)

178
Q

How would you obtain the element at a given point (in x/y coords)?

A

document.elementFromPoint(50, 50)

NOTE: It will pick the element on top, i.e. highest z-index, or if there is no z-index set, the last one in the document order.

179
Q

What properties give you the width and the height of the element being scrolled?

A

scrollWidth and scrollHeight
i.e.

document.body.scrollWidth

180
Q

scrollHeight and scrollWidth gives you the size of the viewport - if you want to know the width and height of an element that is smaller than the scrollable viewport - which properties should you use?

A

clientHeight

clientWidth

181
Q

What do the properties scrollTop and scrollLeft do?

A

They are readable/writable properties that give you the pixels to the left or top that are not currently viewable in the viewport due to scrolling.

182
Q

How would you choose the tenth child element of a content element, and scroll it into view?

A

document.querySelector(‘content’).children[9].scrollIntoView(true);

183
Q

What does the property ‘style’ return?

A

A CSSStyleDeclaration object

184
Q

Does the style property return the CSS on an element?

A

It returns a CSSStyleDeclaration object which only contains inline styles. So you can both set and check inline CSS. But you cannot query the CSS from the external style sheets.

185
Q

How do you set the individual styles of an element?

A

You retrieve the CSSStyleDeclaration object and sets its properties. I.e.

var divStyle = document.querySelector(‘div’).style;

divStyle.backgroundColor = 'red';
divStyle.border = '1px solid black';

NOTE: that we use camel case instead of hyphens for the CSS names.

186
Q

If a CSS property has the same name as a JavaScript native property, what happens to the style. property name?

A

as in the case of ‘float’ - it is given the prefix “css”.

style.cssFloat

187
Q

The CSSStyleDeclaration object also provides methods to change property values - what are they/

A

setPropertyValue()
getPropertyValue()
removeProperty()

188
Q

When using the CSSStyleDeclaration methods that require a style name to be passed, what do we have to remember?

A

They don’t use the modified syntax, i.e. backgroundColor, is background-color - exactly as it would be in CSS.

189
Q

How can you change the inline CSS of a style object in a single line of text?

A

Use the cssText property of the CSSStyleDeclaration object.

190
Q

How would you achieve the same as the following line:

divStyle.cssText = “background-color: red; border-style: 1px solid gray;”

using setAttribute?

A

div.setAttribute(‘style’, ‘background-color: red; border-style: 1px solid gray;’);

191
Q

What is the equivalent of using cssText to get the style value?

A

div.getAttribute(‘style’);

192
Q

How do you get the actual CSS for an element (including any from the cascade)?

A

getComputedStyle()

NOTE: This returns a read-only CSSStyleDeclaration

193
Q

Does getComputedStyle obey the CSS Specificity Hierarchy?

A

Yes - for instance, if a background-color was specified inline to the element, this would be the colour reported by the getComputedStyle(div).backgroundColor - since inline styles are the top of the specificity chart.

194
Q

Is the following valid?

window.getComputedStyle(div).backgroundColor = ‘red’;

A

No - the object returned by getComputedStyle is read only.

195
Q

What is the most common pattern for adding styles to elements in a HTML document?

A

By adding / removing classes using the methods:

div. setAttribute(‘id’, ‘bar’);
div. classList.add(‘foo’);

div. removeAttribute(‘id’);
div. classList.remove(‘foo’);

The id’s and classes basically link the element to predefined CSS.

196
Q

Are textnodes created from whitespace?

A

Yes - if you place whitespace into the document, then you will get a textNode.

197
Q

Are carriage returns considered textNodes?

A

Yes - since they are indeed whitespace.

198
Q

What properties can be used to extract the text from a textNode?

A

data

nodeValue

199
Q

What’s the easiest way to determine the length of a string within a textNode?

A

document. querySelector(‘p’).firstChild.length;
document. querySelector(‘p’).firstChild.data.length;
document. querySelector(‘p’).firstChild.nodeValue.length;

200
Q

What methods can you use to remove / edit etc textNodes?

A
appendData()
deleteData()
insertData()
replaceData()
substringData()
201
Q

Is it possible for multiple sibling textNodes to exist?

A

Yes - although mostly browsers try to combine them intelligently.

But it can happen, particularly when we have a span in the middle of a paragraph. The text either side of the span will be split into their own textNodes. NOTE: The text within the span is not considered a sibling, as it is a child of the span element (which is the ACTUAL sibling to the two textNodes).

The other way it can happen is when you are programmatically adding textnodes to an element that is created programatically in code. If you add two separately, then they will be separate in the DOM.

202
Q

What method is useful for getting the text of the textNodes within an element?

A

textContent

Keep in mind, it gets all text no matter how deep the encapsulating nodes are in the tree.

203
Q

When textContent is used to update an element - what happens to the child nodes within that node?

A

All child nodes are removed, then replacing them with a single textNode.

204
Q

What function can you use to combine multiple textNodes?

A

document.querySelector(‘div’).normalize();

205
Q

How can you split a string (textNode) in the DOM?

A

console.log(document.querySelector(‘p’).firstChild.splitText(4).data);

If the textNode had contained the words “Hey yo!”, ‘yo!’ would have been cut, and ‘Hey’ would have remained.

206
Q

What is a document Fragment?

A

It’s a lightweight version of the dom that lives in memory - it’s not live, but it’s child elements can easily be manipulated in memory, then appended to the live dom.

207
Q

Why is using a document Fragment to create node structures a good way to work?

(especially over the standard createElement())

A

document fragments may contain any type of nodes, whereas an element may not.

It is almost certainly more efficient than using the standard createElement method of creating multiple elements and adding them individually.

208
Q

What’s the basic process of adding nodes via a document fragment?

A

Create fragment
add new nodes to fragment (appendChild)
add fragment to the doc (appendChild)

209
Q

When you add a document fragment to a page (using one of the insertion methods like appendChild) - does the document fragment get added?

A

No - only it’s child node structure.

210
Q

What is one way to speed up the process of creating a node hierarchy using a document fragment?

A

Create a document fragment

Add a div to it (because docfrags don’t have innerHTML themselves).

Use the div’s innerHTML to add a string of HTML

Add the document fragment to the document.

NOTE: You’ll probably want to skip the original div you added in there to allow you to use the innerHTML method.

211
Q

When a document fragment is added to a node, the nodes it contains are removed - how do you keep a copy if you need to do more work on it?

A

You can use the cloneNode(true) method on the document fragment.

212
Q

What two nodes are related to adding style sheets to a document?

A
HTMLStyleElement node (i.e. in html style)
HTMLLinkElement (i.e. using the link element)
213
Q

Each rule within a stylesheet is represented i n the DOM by a…

A

CSSStyleRule object

214
Q

Assuming the link element had an id of #linkElement - how would you get the first CSS style from the style sheet?

A

document.querySelector(‘#linkElement’).sheet.cssRules[0]

215
Q

Is accessing the styles via the link or style elements the same as accessing the CSSStyleSheet object that represents the style sheet?

A

No. In order to do this, you must document.styleSheets

216
Q

How would you determine how many style sheets your document is making use of?

A

document.styleSheets.length

array starting at 0

217
Q

Is styleSheets a live document?

A

Yes - like all Node Lists.

218
Q

What is included in the styleSheets property?

A

All style sheets, both style element and link elements (where rel is set to stylesheet).

219
Q

What is contained within the sheets.cssRules property?

A

A list of CSSStyleRules objects, which gives information about each of the CSS rules contained within the sheet.

220
Q

What methods can be used on the “sheet” property to add and remove new CSS rules?

A

.sheet.insertRule(‘p{color: red;}’, 1);
.sheet.deleteRule(1);

Where the 1 represents the index to be adding / removing the rule.

NOTE: This is relatively uncommon thing to do - as it’s a nightmare to work out the cascading issues from code.

221
Q

We can edit CSS attributes on a node by using style property - can we do this on the CSSStyleRules objects?

A

Yes - each CSSStyleRules object has a style property too.

styleSheet.cssRules[0].style.color

222
Q

What would be the high level description of creating a CSS style sheet on the fly and applying it to a page?

A

Create a new style node
use innerHTML to add CSS rules
and then append the style node to the HTML document (in the head element).

223
Q

How would you add an external CSS style sheet to a page?

A

Create a link tag and fill in the appropriate attributes, before adding it to the HTML document (in the head).

224
Q

How would you disable a stylesheet?

A

Use the disabled property:

document.querySelector(‘#linkElement’).disabled = true;

NOTE: this is not actually an available attribute of link or style element according to the specification. Trying to add this as an actual attribute in the HTML will likely cause an error (and may cause parsing errors where styles are ignored).

225
Q

What happens if you use page inline JavaScript in the same Script tag that you are trying to load a JavaScript file in?

A

The inline (in page) JavaScript will be ignored and the external file will be used.

226
Q

What kind of node does page inline javascript produce?

A

TextNode

227
Q

What happens if you modify the in-page JavaScript via code?

A

If the JavaScript has been parsed, then you just update the text, it will not run the added code - so basically nothing.

228
Q

Should you use self closing Script tags?

A

No - only if you are doing XHTML

229
Q

What are the optional attributes of the script tag?

A

charset, async, defer, src and type.

230
Q

If javascript contains the string (of the closing script element) - what do you have to do?

A

You have to escape the closing slash \/script

Or else it will finish the script right there.

231
Q

By default, when the DOM is parsed, what happens when it hits a script node?

A

It pauses all other downloading of the page, and blocks any further rendering or downloading and executes the javascript. It is considered to be synchronous. This is true even if the file is external (in fact it’s worse).

232
Q

If you use defer on a script tag - when does the JavaScript actually get parsed?

A

Once the HTML node has been parsed.

233
Q

What order are deferred scripts supposed to be executed?

A

According to the specification, document order - however, the actual adherence to this is spotty.

234
Q

What kind of attribute is defer?

A

boolean

235
Q

If you use defer - what javascript method is completely off the table?

A

document.write (as it can only write before the document is completed)

236
Q

If you use the async attribute rather than defer, what happens to the script tags.

A

When a script tag is encountered, it will start downloading the file - it will not parse and execute it until it’s done downloading. Meanwhile the browser continues to load the page / images / HTML.

237
Q

What are the drawbacks of using the async script attribute?

A

Not supported in IE prior to version 10. And the files potentially get parsed out of order leading to dependency issues.

238
Q

If you add defer and async attributes to a script tag - which one is used?

A

async

239
Q

How can you force a browser into asynchronous loading (without using the async tag - and thereby getting around the IE issue)?

A

You can programmatically insert the script elements that contain the JS.

var myscript = document.createElement(‘script’);

myscript. src = ‘myfunkyscript.js’;
document. body.appendChild(myscript);

NOTE: the dependency issue still exists with this method.

240
Q

What attribute of the script tag can you use to notify your script when the javascript has loaded?

A

onload = function() {}

There is of course the:

document.body.onload

load event handler.

241
Q

What are the two main ways to add a click event handler to an element?

A
var elem = document.querySelector('div');
elem.onclick = function(evt) {}

or

elem.addEventListener = (‘click’, function() {});

242
Q

If you place an onclick event on the body (i.e. body.onclick = function() {}) and you click on a div within the page - what happens?

A

The even on the body will fire - as when you click on the div, you are also clicking on the body.

243
Q

What is the downside to using the property event handler?

A

You can only attach one event handler at a time. There are also some subtle issues related to scope chain of the function that is invoked by the event.

244
Q

Property event handler has historically been known as a…

A

DOM Level 0 event

245
Q

addEventListener event handler has historically been known as…

A

DOM Level 2 event

246
Q

Inline event handlers are sometimes known as…

A

HTML event handlers

247
Q

What’s the difference between the blur and the focus events?

A

Blur is used when an element loses focus, focus is when it gains focus.

248
Q

What are the different phases that occur when processing events?

A

Capture phase
Target phase
Bubbling phase

249
Q

Which phase is the most commonly exploited of the event phases?

A

bubbling

250
Q

What are bubbling and capturing?

A

They are two different methods of propagating events in the JavaScript system.

NOTE: capturing is also known as trickling - which can help remember the order.

trickle down
bubble up

251
Q

What is the difference between bubbling and capturing?

A

With capturing - events are first captured by the outer most elements - and propagated down.

With bubbling events are captured by the inner most elements and propagated out.

252
Q

How do you choose between the bubbling and capturing models?

A

Using the addEventListener function

addEventListener(type, handler, useCapture)

set the third parameter to true to use capturing.

253
Q

Why might you choose to use bubbling over capturing?

A

Capturing is not available in IE9 and lower.

254
Q

Why might you choose to use capture over bubbling?

A

In complex DOM’s bubbling is probably less efficient.

255
Q

Why might event capturing be useful?

A

It allows you to intercept the message before it reaches the target.

256
Q

How can you determine what phase an event was handled in?

A

The event listener functions recieve and event object which has a property called eventPhase. This has a number that identifies the phase:

1 - capture phase
2 - target phase
3 - bubbling phase

257
Q

Can the addEventListener method be used on XMLHttpRequest?

A

Yes

258
Q

How do you remove an event listener?

A

Use removeEventListener

259
Q

What is the gotcha with removing event listeners?

A

You can’t remove an event listener that was created with an anonymous function.

260
Q

The value of ‘this’ inside an event listener is usually what?

A

The object the event is attached too.

261
Q

If you have an event handler on a couple of elements that wrap each other (i.e. a p within a div, within the body) - what will the ‘this’ value be in the case of bubbling (or capturing)?

A

It’s the value of the element that receives the event. So if you click on p - when the event attached to the div fires, the this value will be div.

262
Q

What is another way of getting the same value that is pointed to by this within an event handler function?

A

event.eventTarget

The value passed into the event handler has a reference to the “eventTarget” parameter - which is the same value as this.

263
Q

How would you determine where an event originated from?

A

The event object passed to the event handler has a property called ‘target’.

264
Q

If we had a click event handler on the body, and then click on a div (with no event handler) within the body - what will be reported by:

‘console.log(event.target)’

A

The div

.target references the target of the event, not necessarily the one that caught the event.

265
Q

Why would Event.target be useful?

A

You can use it for event delegation. Say for instance you want to hide an element in a list if it is clicked. But you didn’t want to put an event handler on every item in that list.

You could put an event handler on the parent of that list - and when the event bubbles up, use the event.target to hide it.

event.target.style.visibillity = “none”

266
Q

What method do you use to prevent the browser from executing the default action on the built in event handlers (like clicking a link)?

A

Event.preventDefault()

267
Q

What is important to remember about preventDefault()?

A

The event itself is stopped, but the event still propagates (so my trigger other events elsewhere).

268
Q

What is another way of preventing the default event occuring, other than using preventDefault?

A

You can return false at the end of the function.

269
Q

There is a property in the Event object named cancelable - what does this do?

A

This is a boolean property that indicates whether the event will respond to preventDefault()

270
Q

What does ‘stopImmediatePropagation’ do?

A

Stops any subsequent triggering of events of the same type for that particular action. i.e. if you add five event listeners, all for the ‘click’ event on a single div - and the second one added uses stopImmediatePropagation - then the third, fourth and fifth event handlers will not fire.

271
Q

Does stopImmediatePropagation stop default events occurring?

A

No, browser events will still occur.

272
Q

What is the basic process of creating a custom event?

A

Create an event using createEvent
Add an event to the element - giving it a custom name
call initCustomEvent (specifying the custom event name)
Later, use dispatchEvent to trigger it.

273
Q

What is the parameter that you must send to document.createEvent

A

‘CustomEvent’

274
Q

How would you simulate a mouse click?

A

First setup the normal click event on the element (or whateve event you want to trigger).

create a simulated mouse click using createEvent(‘MouseEvents’);

Then use initMouseEvent to initialise the event.

call dispatchEvent on the element, passing it the mouse event.

275
Q

Click events are fairly easy to simulate - however other events are very tricky - what libraries’ can you use to do this for you?

A

jQuery (trigger method)
or
simulate.js

276
Q

What is one implication (regarding creation of elements) regarding event delegation?

A

The target elements do not need to be in the dom when the event is created (because the event is attached to an element further up / down the tree)

i.e. we can add an event to the table - all clicks on the table cells are then propagated and captured by the table cell, rather than the individual cells. This allows for one event handler to deal with many different targets.

277
Q

If we were to set a table element (table) to be a delegate - how can we be sure we are getting messages just from the TD’s within the table?

A

Check the tagname.

if (event.target.tagName.toLowerCase() === ‘td’) {
}

278
Q

Event delegation is idealy leveraged when we are dealing with event types such as…

A

click, mousedown, mouseup, keydown, keyup, and keypress