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
What event can be used to load content after the document is fully loaded?
DOMContentLoaded document.addEventListener("DOMContentLoaded", funcName, false);
26
How can you use array index notation to access the first element in a group of tags?
var myElement = document.getElementsByTagName('p')[0];
27
How could you reach the last element in an array returned by getElementsByClassName?
``` var elements = document.getElementsByClassName('foobar'); element = elements[elements.length - 1]; ```
28
What does the property nodeType (on an element) tell us?
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
29
What does the nodeName property provide us?
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.
30
What does the property nodeValue provide us?
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.
31
Can the nodeValue of text nodes be read and set?
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";
32
What property contains the list of children nodes for an element?
childNodes
33
What is important to realise about childNodes property?
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.
34
The properties yourElement.firstChild / lastChild are simply what??
Short cuts that are the same as: yourElement.childNodes[0] and yourElement.childNodes[yourElement.childNodes.length - 1]
35
How can you determine whether a node has child nodes?
The function hasChildNodes() - which returns a boolean value.
36
Line breaks can sometimes show up as..
#text - they look like text nodes, but are not.
37
How do you get access to an elements parent node?
Use the parentNode property.
38
How could you test to see if an element is within a parent element with the class "dynamic"
``` var myLinkedItem = document.getElementById('linkedItem'); var parentElem = myLinkedItem.parentNode; ``` while (!parentElem.className != 'dynamic' && parentElem != document.body) { parentElem = parentElem.parentNode; }
39
What methods are used to check sibling elements?
``` var myLink = document.getElementById('foobar'); var next = myLink.nextSibling; var prev = myLink.previousSibling; ```
40
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?
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).
41
When the setting of the property nodeValue is null - what effect does setting it have?
None.
42
When should you use innerHTML to set text?
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.
43
Can you link getElement calls together to narrow down the search?
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');
44
All HTML attributes defined in the standard can be accessed via properties - why might some be read only?
Security reasons.
45
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')
var image = document.getElementById('nav').getElementsByTagName('img')[0]; image.alt = "changed!";
46
Some HTML attribute properties have the same name as reserved words in JavaScript - (i.e. for, and class) - how do you deal with this?
You use the approved names for JavaScript / DOM. ``` for might be htmlFor and class is className ```
47
Instead of using properties, you can change the elements attributes using DOM functions - what are they?
getAttribute('attr'); | setAttribute('attr', value);
48
What does document.createElement('a') do?
Creates a new element of type a - a link.
49
What does document.createTextNode('string') do?
Creates a new text node that contains the string, 'string'.
50
What does node.appendChild(newnode); do?
Creates a new node that is added as a child to a node, and following any existing nodes.
51
What does newNode = node.cloneNode(true); do?
Clones a node - if the parameter is true, it clones any child nodes.
52
What does node.insertBefore(newNode, oldNode); do?
inserts newNode as a child of node and before oldNode
53
What does node.removeChild(oldNode); do?
Removes the child oldNode from node
54
What does node.replaceChild(newNode, oldNode); do
Replaces the childNode, oldNode of node;
55
What does node.value do?
Returns the current value of the node;
56
Is script or not script tags valid in the body of the HTML?
No - it's not semmantically correct
57
Rather than using no-script, (which is now deprecated) - how do you tell your users that there is a problem with JS?
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.
58
Does the create (createElement etc) functions actually add an element to the page?
No - it just creates an element ready for insertion.
59
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?
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).
60
The meta charset declaration should be...
before any elements that contain text.
61
What are the most common node types?
``` DOCUMENT_NODE ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE DOCUMENT_FRAGMENT_NODE DOCUMENT_TYPE_NODE ```
62
If you were interested in seeing the numerical values of the node types - how could you do it?
You can use the Node object - Node.ELEMENT_NODE. These are basically constants / enums.
63
What is the risk with using Node properties and methods on attributes?
The ATTRIBUTE_NODE is being deprecated in DOM4. Attr used to inherit from Node in DOM1, 2 and 3.
64
Do all node types inherit from Node?
No
65
What is the alternative to using getElementById, getElementsByClass etc?
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.
66
What value is TEXT_NODE?
3
67
What value is DOCUMENT_NODE?
9
68
What value is DOCUMENT_TYPE_NODE?
10
69
What value is ELEMENT_NODE?
1
70
What value is DOCUMENT_FRAGMENT_VALUE?
11
71
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?
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.
72
Why should createAttribute no longer be used?
It's deprecated.
73
What is the replacement for createAttribute?
getAttribute setAttribute removeAttribute
74
What function can be used to create comment nodes?
createComment
75
What property of an element can you use to replace the element type?
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.
76
innerText and textContent appear to do the same thing - what's the differences?
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.
77
What does the insertAdjacentHTML function do?
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.
78
What are the four positions that insertAdjacentHTML provides?
beforebegin afterbegin beforeend afterend NOTE: Beforebegin and afterend only works if the node is in a tree and has an element parent.
79
What is the major difference between the textContent property and the insertAdjacentHTML function?
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.
80
Does document.write stall/pause the page parsing during load?
Yes.
81
Why should you use innerHTML / outerHTML sparingly?
They invoke a rather heavy HTML parser
82
Support for outerHTML is not available in Firefox until version 11 - how do you fix this if you need to support earlier versions?
There is a polyfill available.
83
With regards to hidden elements (i.e. through CSS) - what is the difference between innerText and textContent?
textContent is not aware of styles and will return hidden text - whereas innerText will not.
84
Related to insertAdjacentHTML is the functions insertAdjacentElement and insertAdjacentText, what are the problems with these functions?
They are not available in firefox at all.
85
What is the difference between innerText and outerText?
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.
86
insertBefore requires two parameters, what happens if you don't pass the second parameter?
It behaves exactly like appendChild
87
Why is removing a node (i.e. removeChild) a multistep process?
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.
88
How is removeChild and replaceChild similar?
You must do it in a multistep process. Select the node, select the parent, and from there - replaceChild (or removeChild).
89
When you use a function like getElementsByTagName, what is returned?
A NodeList
90
What is the difference between a NodeList and an array?
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.
91
How do you convert a NodeList to an array?
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 ```
92
Why does calling appendChild in a loop with a NodeList fail?
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.
93
What does calling slice on an array, with no parameters do?
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);
94
What is a big difference between slice and splice?
slice does not mutate the array - however, splice does.
95
When you clone a node using cloneNode - what events are copied across?
Any inline events - anything that was attached by using 'addEventListener', or node.onClick, will not be copied.
96
What is the risk with using cloneNode?
You may get duplicate ID's in the document.
97
When you select a group of nodes from the DOM tree - they can be one of two types - what are they?
NodeList | HTMLCollection
98
A collection can either be...
live or static | i.e. live means it's still part of the actual document, static means its just a snapshot
99
What property exists on a collection that allows you to determine how many nodes are within it?
.length
100
What version of ECMAScript was []. implemented in?
5 So don't expect this to work on pre-IE9 browsers. You are better off using Array.
101
When using .childNodes - what do you have to be aware of regarding the nodes being returned?
They aren't going to be just element nodes. It will contain comment and text nodes as well.
102
What variable can you use to get a HTMLCollection of all the links on the document?
document.links
103
What version of ECMAScript was Array.isArray found in?
5 So again - you can't go using this on pre IE9 browsers.
104
What is the benefit of converting a NodeList to an array?
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.
105
Currently we have to use slice to convert an array like object to an actual array. What is the ECMAScript 6 variant?
Array.from
106
What are the properties we can use to traverse the DOM?
``` parentNode firstChild lastChild nextSibling previousSibling ```
107
Using the properties firstChild etc, it includes things like text nodes and comments. How can you get around this?
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.
108
How do you determine if a node is contained within another node?
document.getElementsByTagName('ul')[0].contains(node); NOTE: It returns true only if the node passed and the node selected are identical.
109
You can compare the document position of two nodes, using the compareDocumentPosition() function. What are the return results it gives?
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
110
Two nodes are equal, if and only if...
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
111
How do you compare two nodes?
You can use the method isEqualNode
112
What's one gotcha of using the livepreview of brackets when testing for perfect equality of two nodes (i.e. using isEqualNode)?
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
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?
Just use the equality operator === i.e. document.body === document.body
114
What constructor is used to create the document node?
HTMLDocument()
115
How would you get the referrer of a document?
document.referrer
116
How would you get the title of a document
document.title
117
How would you get the current compatibility mode?
document.compatMode Returns either CSS1Compat (strict mode) - or BackCompat (quirks mode)
118
What nodes are typically returned from document.childNodes?
one doctype node | one element node (the HTML element for the document)
119
Is the window.document the same as the Document object?
No - the window.document is created using the HTMLDocument constructor - and not the Document object.
120
windows.document provides shortcuts to a few elements, what are some of them?
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
How can we determine what type of DOM level a browser supports?
if (document.implementation.hasFeature('Core', '3.0');
122
What are the options you can check for in implementation.hasFeature?
``` Core (DOM level) XML HTML Views StyleSheets etc. etc. ``` And many others. Look up documentation on hasFeature to determine the values to expect.
123
hasFeature is useful, but can you trust it alone?
No - you must really use capability detection along with it.
124
How do you set an element to be 'focused'?
document.querySelector('textarea').focus();
125
How do you get a reference to the currently selected element?
document.activeElement
126
How can you determine if the current page has focus?
document.hasFocus()
127
The document.defaultView property is a shortcut to what?
The head or global object. In a web browser, that's window - in a javascript browser environment, defaultView will point to this.
128
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?
Use document.defaultView
129
Each element in a HTML document has a unique behavior - therefore they require unique...
JavaScript constructors.
130
What's one way to determine the constructor that was used on an element?
document.querySelector('a').constructor;
131
All of the constructors for HTML elements (HTML*Element) - of which there are many, inherit from what objects?
HTMLElement, Element, Node and Object
132
What does Object.keys() do?
Returns the enumerable properties (in an array) on the given object.
133
The function createElement creates a new DOM element, can you pass it mixed case names for the elements?
Yes - but they are all smashed to lowercase anyway before the element is created.
134
You can use nodeName to get the name of a node - what other method can be used?
tagName
135
What is the difference between tagName and nodeName?
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
If you have a comment node named 'comment' - is this code valid? comment.tagName?
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
How can you get the attributes of an element?
document.querySelector('a').attributes;
138
What does .attributes return?
A NamedNodeMap - it's live, very much like a NodeList - so changing it will change the values of the attributes.
139
If you had an array of attributes - how would you change the value of the href in the live document?
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
NamedNodeMap has a number of methods that are useful for adding / removing attributes - what are they?
getNamedItem() setNamedItem() removeNamedItem() NOTE: It's probably preferable to use getAttribute, setAttribute, hasAttribute and removeAttribute directly from the node itself.
141
What method can be used to determine if a node has an attribute?
.hasAttribute()
142
Should you use removeAttribute, or setAttribute('');
Always use removeAttribute. This also goes for setting the attributes nodeValue to null (don't do it).
143
What is the best way to make sure an element has a specific attribute?
use the hasAttribute method.
144
if you have an attribute - but it's value is not set - what will hasAttribute return?
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
There are two ways to get the list of classes from a node element - what are they?
className | classList
146
What is the problem with className?
It provides a space separated list that you have to process to get the classnames.
147
What is the problem with classList?
Only supported from IE10 upwards - not perfect support.
148
What kind of list does classList return?
DOMTokenList
149
Is classList an array or arraylike object?
It's an array like object.
150
Using classList how do you add, or remove a class?
classList.add('classname'); | classList.remove('classname');
151
Using className, how do you add / remove classes?
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
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?
var elm = document.querySelector('div'); elm.classList.contains('brown')
153
If you save data on a HTML element, like such: elm.dataset.gooGoo = 'goo'; What does the actual element look like in HTML?
goo-goo="goo" NOTE: The camel casing is changed to hyphens. This goes for reading the data too.
154
How do you read the data from an element?
elm.dataset.gooGoo | Where gooGoo is an attribute named "data-goo-goo" on the element.
155
Because dataset is not available in IE9 (there is a polyfil though) - what can you use instead?
getAttribute('data-foo'); setAttribute('data-foo'); hasAttribute('data-foo'); removeAttribute('data-foo');
156
How do you delete a data attribute using data-set?
delete dataset.fooFoo
157
Why is querySelector better than getElementById?
querySelector has a more robust selection mechanism and can use CSS selectors.
158
Why is querySelector worse than getElementById?
It's not supported as widely (IE8 and above - although IE8 only has CSS 2.1 support).
159
What are the most common methods of selecting a DOM element?
document. querySelector('a'); | document. getElementById('myid');
160
What is the most common method of selecting a list of nodes in a document?
document. querySelectorAll() document. getElementsByTagName() document. getElementsByClassName()
161
What is the main difference in the return value from querySelectorAll - and getElementsByTagName?
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
querySelectorAll, getElementsByTagName, getElementsByClassName are all defined on individual element nodes - what does this imply?
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
What does getElementsByName do?
It allows you to select elements that make use of the name attribute. form, img, frame, embed, object elements all use name.
164
What is the difference between a NodeList and a HTMLCollection?
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
What is the difference between the properties, children and childNodes?
.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
HTMLCollections contain elements in what order?
Document order, i.e. the order they appear in the document.
167
What are some of the preconfigured legacy arrays that are available from the document root?
document. all document. forms document. images document. links document. scripts document. stylesheets
168
What datatype are most of the preconfigured legacy arrays (i.e. document.links)?
HTMLCollection interface / objects
169
What datatype is the document.stylesheets preconfigured array?
StyleSheetList
170
What is something to keep in mind about doucment.all?
A) it's not constructed from a HTMLCollection, it is constructed from a HTMLAllCollection B) it's not supported in firefox.
171
Is there a way to determine whether a given element will match a specific CSS selector?
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
What is the CSSOM View Module?
An API that allows the modification of the visual representation within the browser of the DOM.
173
The value of offsetLeft is measured from where?
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
What methods can be used to get the elements top, right, and left border edge offsets relative to the viewport?
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
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?
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
offsetHeight and offsetWidth include the width of the borders - how would you get this value without the border widths?
Use clientHeight and clientWidth
177
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?
75px 75px 25px padding + 25px content + 25px padding (borders are not included, nor are margins)
178
How would you obtain the element at a given point (in x/y coords)?
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
What properties give you the width and the height of the element being scrolled?
scrollWidth and scrollHeight i.e. document.body.scrollWidth
180
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?
clientHeight | clientWidth
181
What do the properties scrollTop and scrollLeft do?
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
How would you choose the tenth child element of a content element, and scroll it into view?
document.querySelector('content').children[9].scrollIntoView(true);
183
What does the property 'style' return?
A CSSStyleDeclaration object
184
Does the style property return the CSS on an element?
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
How do you set the individual styles of an element?
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
If a CSS property has the same name as a JavaScript native property, what happens to the style. property name?
as in the case of 'float' - it is given the prefix "css". style.cssFloat
187
The CSSStyleDeclaration object also provides methods to change property values - what are they/
setPropertyValue() getPropertyValue() removeProperty()
188
When using the CSSStyleDeclaration methods that require a style name to be passed, what do we have to remember?
They don't use the modified syntax, i.e. backgroundColor, is background-color - exactly as it would be in CSS.
189
How can you change the inline CSS of a style object in a single line of text?
Use the cssText property of the CSSStyleDeclaration object.
190
How would you achieve the same as the following line: divStyle.cssText = "background-color: red; border-style: 1px solid gray;" using setAttribute?
div.setAttribute('style', 'background-color: red; border-style: 1px solid gray;');
191
What is the equivalent of using cssText to get the style value?
div.getAttribute('style');
192
How do you get the actual CSS for an element (including any from the cascade)?
getComputedStyle() NOTE: This returns a read-only CSSStyleDeclaration
193
Does getComputedStyle obey the CSS Specificity Hierarchy?
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
Is the following valid? window.getComputedStyle(div).backgroundColor = 'red';
No - the object returned by getComputedStyle is read only.
195
What is the most common pattern for adding styles to elements in a HTML document?
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
Are textnodes created from whitespace?
Yes - if you place whitespace into the document, then you will get a textNode.
197
Are carriage returns considered textNodes?
Yes - since they are indeed whitespace.
198
What properties can be used to extract the text from a textNode?
data | nodeValue
199
What's the easiest way to determine the length of a string within a textNode?
document. querySelector('p').firstChild.length; document. querySelector('p').firstChild.data.length; document. querySelector('p').firstChild.nodeValue.length;
200
What methods can you use to remove / edit etc textNodes?
``` appendData() deleteData() insertData() replaceData() substringData() ```
201
Is it possible for multiple sibling textNodes to exist?
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
What method is useful for getting the text of the textNodes within an element?
textContent Keep in mind, it gets all text no matter how deep the encapsulating nodes are in the tree.
203
When textContent is used to update an element - what happens to the child nodes within that node?
All child nodes are removed, then replacing them with a single textNode.
204
What function can you use to combine multiple textNodes?
document.querySelector('div').normalize();
205
How can you split a string (textNode) in the DOM?
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
What is a document Fragment?
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
Why is using a document Fragment to create node structures a good way to work? (especially over the standard createElement())
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
What's the basic process of adding nodes via a document fragment?
Create fragment add new nodes to fragment (appendChild) add fragment to the doc (appendChild)
209
When you add a document fragment to a page (using one of the insertion methods like appendChild) - does the document fragment get added?
No - only it's child node structure.
210
What is one way to speed up the process of creating a node hierarchy using a document fragment?
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
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?
You can use the cloneNode(true) method on the document fragment.
212
What two nodes are related to adding style sheets to a document?
``` HTMLStyleElement node (i.e. in html style) HTMLLinkElement (i.e. using the link element) ```
213
Each rule within a stylesheet is represented i n the DOM by a...
CSSStyleRule object
214
Assuming the link element had an id of #linkElement - how would you get the first CSS style from the style sheet?
document.querySelector('#linkElement').sheet.cssRules[0]
215
Is accessing the styles via the link or style elements the same as accessing the CSSStyleSheet object that represents the style sheet?
No. In order to do this, you must document.styleSheets
216
How would you determine how many style sheets your document is making use of?
document.styleSheets.length | array starting at 0
217
Is styleSheets a live document?
Yes - like all Node Lists.
218
What is included in the styleSheets property?
All style sheets, both style element and link elements (where rel is set to stylesheet).
219
What is contained within the sheets.cssRules property?
A list of CSSStyleRules objects, which gives information about each of the CSS rules contained within the sheet.
220
What methods can be used on the "sheet" property to add and remove new CSS rules?
.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
We can edit CSS attributes on a node by using style property - can we do this on the CSSStyleRules objects?
Yes - each CSSStyleRules object has a style property too. styleSheet.cssRules[0].style.color
222
What would be the high level description of creating a CSS style sheet on the fly and applying it to a page?
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
How would you add an external CSS style sheet to a page?
Create a link tag and fill in the appropriate attributes, before adding it to the HTML document (in the head).
224
How would you disable a stylesheet?
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
What happens if you use page inline JavaScript in the same Script tag that you are trying to load a JavaScript file in?
The inline (in page) JavaScript will be ignored and the external file will be used.
226
What kind of node does page inline javascript produce?
TextNode
227
What happens if you modify the in-page JavaScript via code?
If the JavaScript has been parsed, then you just update the text, it will not run the added code - so basically nothing.
228
Should you use self closing Script tags?
No - only if you are doing XHTML
229
What are the optional attributes of the script tag?
charset, async, defer, src and type.
230
If javascript contains the string (of the closing script element) - what do you have to do?
You have to escape the closing slash \/script Or else it will finish the script right there.
231
By default, when the DOM is parsed, what happens when it hits a script node?
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
If you use defer on a script tag - when does the JavaScript actually get parsed?
Once the HTML node has been parsed.
233
What order are deferred scripts supposed to be executed?
According to the specification, document order - however, the actual adherence to this is spotty.
234
What kind of attribute is defer?
boolean
235
If you use defer - what javascript method is completely off the table?
document.write (as it can only write before the document is completed)
236
If you use the async attribute rather than defer, what happens to the script tags.
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
What are the drawbacks of using the async script attribute?
Not supported in IE prior to version 10. And the files potentially get parsed out of order leading to dependency issues.
238
If you add defer and async attributes to a script tag - which one is used?
async
239
How can you force a browser into asynchronous loading (without using the async tag - and thereby getting around the IE issue)?
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
What attribute of the script tag can you use to notify your script when the javascript has loaded?
onload = function() {} There is of course the: document.body.onload load event handler.
241
What are the two main ways to add a click event handler to an element?
``` var elem = document.querySelector('div'); elem.onclick = function(evt) {} ``` or elem.addEventListener = ('click', function() {});
242
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?
The even on the body will fire - as when you click on the div, you are also clicking on the body.
243
What is the downside to using the property event handler?
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
Property event handler has historically been known as a...
DOM Level 0 event
245
addEventListener event handler has historically been known as...
DOM Level 2 event
246
Inline event handlers are sometimes known as...
HTML event handlers
247
What's the difference between the blur and the focus events?
Blur is used when an element loses focus, focus is when it gains focus.
248
What are the different phases that occur when processing events?
Capture phase Target phase Bubbling phase
249
Which phase is the most commonly exploited of the event phases?
bubbling
250
What are bubbling and capturing?
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
What is the difference between bubbling and capturing?
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
How do you choose between the bubbling and capturing models?
Using the addEventListener function addEventListener(type, handler, useCapture) set the third parameter to true to use capturing.
253
Why might you choose to use bubbling over capturing?
Capturing is not available in IE9 and lower.
254
Why might you choose to use capture over bubbling?
In complex DOM's bubbling is probably less efficient.
255
Why might event capturing be useful?
It allows you to intercept the message before it reaches the target.
256
How can you determine what phase an event was handled in?
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
Can the addEventListener method be used on XMLHttpRequest?
Yes
258
How do you remove an event listener?
Use removeEventListener
259
What is the gotcha with removing event listeners?
You can't remove an event listener that was created with an anonymous function.
260
The value of 'this' inside an event listener is usually what?
The object the event is attached too.
261
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)?
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
What is another way of getting the same value that is pointed to by this within an event handler function?
event.eventTarget The value passed into the event handler has a reference to the "eventTarget" parameter - which is the same value as this.
263
How would you determine where an event originated from?
The event object passed to the event handler has a property called 'target'.
264
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)'
The div .target references the target of the event, not necessarily the one that caught the event.
265
Why would Event.target be useful?
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
What method do you use to prevent the browser from executing the default action on the built in event handlers (like clicking a link)?
Event.preventDefault()
267
What is important to remember about preventDefault()?
The event itself is stopped, but the event still propagates (so my trigger other events elsewhere).
268
What is another way of preventing the default event occuring, other than using preventDefault?
You can return false at the end of the function.
269
There is a property in the Event object named cancelable - what does this do?
This is a boolean property that indicates whether the event will respond to preventDefault()
270
What does 'stopImmediatePropagation' do?
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
Does stopImmediatePropagation stop default events occurring?
No, browser events will still occur.
272
What is the basic process of creating a custom event?
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
What is the parameter that you must send to document.createEvent
'CustomEvent'
274
How would you simulate a mouse click?
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
Click events are fairly easy to simulate - however other events are very tricky - what libraries' can you use to do this for you?
jQuery (trigger method) or simulate.js
276
What is one implication (regarding creation of elements) regarding event delegation?
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
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?
Check the tagname. if (event.target.tagName.toLowerCase() === 'td') { }
278
Event delegation is idealy leveraged when we are dealing with event types such as...
click, mousedown, mouseup, keydown, keyup, and keypress