JavaScript DOM Flashcards
If you use parseInt on the value “345ss”, what will you get?
345 - it will ignore the string in it.
If you use parseInt on the value “345s4s”, what will you get?
345 - it will stop at the first non numerical character
If you use parseInt on the value “s345ss”, what will you get?
NaN - it will determine that the value is not a number because the first character is a char.
What month would be printed out with the following declaration?
var someDate = new Date(2015, 9, 22, 9);
October - months are 0 indexed… for some reason…
the Date object has some useful methods, what would you use to extract the full year?
dateObject.getFullYear()
If the month is set to 0 (jan), and you call someDate.setDate(32); - what is the result?
It will give you Feb, 1st. The system is smart enough to wrap the value around.
What’s an alternative to using Number on a string to convert it?
Subtract 0. This will coerce the string to a number
Why would you populate the JS Date object from serverside data, rather than relying on the JavaScript Date object?
Because you can’t be sure the client side computer is set up correctly.
Given the following code, what will be printed out?
var myarray = [1, 2, 3, 4, 5, 6, 7];
console.log(myarray.slice(1, 4));
2, 3, 4
NOTE: the indexes are zero based. And in the slice function, the first parameter is inclusive, the second is not
var myarray = [1, 2, 3, 4, 5, 6, 7];
console.log(myarray.slice(3));
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.
What is a significant use of the array’s join and split functions?
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
Is the sort method of the array object destructive?
Yes - it will modify the original array
How do you compare two string objects using the == operator?
string1.valueOf() == string2.valueOf();
Without this we would be comparing two string objects which would return false as they are indeed different objects.
In a traditional web application, where does the business logic live?
On the server.
In a traditional web application, where does the content layer live?
On the server
What is one reason to not embed javascript into the script tags of a HTML page?
Because a script error could prevent the page from loading.
What is the security reason to keep JS in separate files?
The CSP - content security policy will make sure only the code being run from separate files will be run.
What variable holds the browser name / version?
navigator. appName
navigator. appVersion
Browser sniffing is a bad way to determine funtionality - what is the recommended way?
Object detection
if (functionalityIwant) {
}
What can you use to determine whether the browser supports the currently recommended W3C DOM level?
if (document.getElementById) { // It's a modern browser }
If you need to test for older IE browsers - you can use document.all
What are the layers involved in “progressive enhancement”
- Semantically valid HTML
- CSS
- JavaScript - starts when document is loaded
- JavaScript - check that W3C DOM is available
- JavaScript - Check that desired components are avail.
What are some key things to think about with regards to JavaScript and accessibility?
- All content should be available with/without JS
- If there is content or functionality that only makes with JS, then the elements must be created by JS (i.e. no hanging buttons).
- JS functionality should be independent of user input
- If you make non interactive elements into interactive elements, there should be a fall back
- Scripts should not redirect, or submit without user interaction
What is the shortcomings of using document.write?
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.
Can you retrieve elements with different class names using getElementsByClassName?
Yes - you just pass multiple class names to the function.
var elements = document.getElementsByClassName(“foo bar”);
What event can be used to load content after the document is fully loaded?
DOMContentLoaded
document.addEventListener(“DOMContentLoaded”, funcName, false);
How can you use array index notation to access the first element in a group of tags?
var myElement = document.getElementsByTagName(‘p’)[0];
How could you reach the last element in an array returned by getElementsByClassName?
var elements = document.getElementsByClassName('foobar'); element = elements[elements.length - 1];
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
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.
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.
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”;
What property contains the list of children nodes for an element?
childNodes
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.
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]
How can you determine whether a node has child nodes?
The function hasChildNodes() - which returns a boolean value.
Line breaks can sometimes show up as..
text - they look like text nodes, but are not.
How do you get access to an elements parent node?
Use the parentNode property.
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;
}
What methods are used to check sibling elements?
var myLink = document.getElementById('foobar'); var next = myLink.nextSibling; var prev = myLink.previousSibling;
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).
When the setting of the property nodeValue is null - what effect does setting it have?
None.
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.
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’);
All HTML attributes defined in the standard can be accessed via properties - why might some be read only?
Security reasons.
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!”;
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
Instead of using properties, you can change the elements attributes using DOM functions - what are they?
getAttribute(‘attr’);
setAttribute(‘attr’, value);
What does document.createElement(‘a’) do?
Creates a new element of type a - a link.
What does document.createTextNode(‘string’) do?
Creates a new text node that contains the string, ‘string’.
What does node.appendChild(newnode); do?
Creates a new node that is added as a child to a node, and following any existing nodes.
What does newNode = node.cloneNode(true); do?
Clones a node - if the parameter is true, it clones any child nodes.
What does node.insertBefore(newNode, oldNode); do?
inserts newNode as a child of node and before oldNode
What does node.removeChild(oldNode); do?
Removes the child oldNode from node
What does node.replaceChild(newNode, oldNode); do
Replaces the childNode, oldNode of node;
What does node.value do?
Returns the current value of the node;
Is script or not script tags valid in the body of the HTML?
No - it’s not semmantically correct
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.
Does the create (createElement etc) functions actually add an element to the page?
No - it just creates an element ready for insertion.
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).
The meta charset declaration should be…
before any elements that contain text.
What are the most common node types?
DOCUMENT_NODE ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE DOCUMENT_FRAGMENT_NODE DOCUMENT_TYPE_NODE
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.
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.
Do all node types inherit from Node?
No
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.
What value is TEXT_NODE?
3
What value is DOCUMENT_NODE?
9
What value is DOCUMENT_TYPE_NODE?
10
What value is ELEMENT_NODE?
1
What value is DOCUMENT_FRAGMENT_VALUE?
11
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.
Why should createAttribute no longer be used?
It’s deprecated.
What is the replacement for createAttribute?
getAttribute
setAttribute
removeAttribute
What function can be used to create comment nodes?
createComment
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.
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.
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.
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.
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.
Does document.write stall/pause the page parsing during load?
Yes.
Why should you use innerHTML / outerHTML sparingly?
They invoke a rather heavy HTML parser
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.
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.
Related to insertAdjacentHTML is the functions insertAdjacentElement and insertAdjacentText, what are the problems with these functions?
They are not available in firefox at all.
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.
insertBefore requires two parameters, what happens if you don’t pass the second parameter?
It behaves exactly like appendChild
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.
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).
When you use a function like getElementsByTagName, what is returned?
A NodeList
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.
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
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.
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);
What is a big difference between slice and splice?
slice does not mutate the array - however, splice does.
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.
What is the risk with using cloneNode?
You may get duplicate ID’s in the document.
When you select a group of nodes from the DOM tree - they can be one of two types - what are they?
NodeList
HTMLCollection
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
What property exists on a collection that allows you to determine how many nodes are within it?
.length
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.
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.
What variable can you use to get a HTMLCollection of all the links on the document?
document.links
What version of ECMAScript was Array.isArray found in?
5
So again - you can’t go using this on pre IE9 browsers.
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.
Currently we have to use slice to convert an array like object to an actual array. What is the ECMAScript 6 variant?
Array.from
What are the properties we can use to traverse the DOM?
parentNode firstChild lastChild nextSibling previousSibling
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.
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.
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
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
How do you compare two nodes?
You can use the method isEqualNode
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.
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
What constructor is used to create the document node?
HTMLDocument()
How would you get the referrer of a document?
document.referrer
How would you get the title of a document
document.title
How would you get the current compatibility mode?
document.compatMode
Returns either CSS1Compat (strict mode) - or BackCompat (quirks mode)
What nodes are typically returned from document.childNodes?
one doctype node
one element node (the HTML element for the document)
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.
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
How can we determine what type of DOM level a browser supports?
if (document.implementation.hasFeature(‘Core’, ‘3.0’);
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.
hasFeature is useful, but can you trust it alone?
No - you must really use capability detection along with it.
How do you set an element to be ‘focused’?
document.querySelector(‘textarea’).focus();
How do you get a reference to the currently selected element?
document.activeElement
How can you determine if the current page has focus?
document.hasFocus()
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.
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
Each element in a HTML document has a unique behavior - therefore they require unique…
JavaScript constructors.
What’s one way to determine the constructor that was used on an element?
document.querySelector(‘a’).constructor;
All of the constructors for HTML elements (HTML*Element) - of which there are many, inherit from what objects?
HTMLElement, Element, Node and Object
What does Object.keys() do?
Returns the enumerable properties (in an array) on the given object.
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.
You can use nodeName to get the name of a node - what other method can be used?
tagName
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.
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.
How can you get the attributes of an element?
document.querySelector(‘a’).attributes;
What does .attributes return?
A NamedNodeMap - it’s live, very much like a NodeList - so changing it will change the values of the attributes.
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
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.
What method can be used to determine if a node has an attribute?
.hasAttribute()
Should you use removeAttribute, or setAttribute(‘’);
Always use removeAttribute.
This also goes for setting the attributes nodeValue to null (don’t do it).
What is the best way to make sure an element has a specific attribute?
use the hasAttribute method.
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.
There are two ways to get the list of classes from a node element - what are they?
className
classList
What is the problem with className?
It provides a space separated list that you have to process to get the classnames.
What is the problem with classList?
Only supported from IE10 upwards - not perfect support.
What kind of list does classList return?
DOMTokenList
Is classList an array or arraylike object?
It’s an array like object.
Using classList how do you add, or remove a class?
classList.add(‘classname’);
classList.remove(‘classname’);
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)’) ,’’);}
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’)
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.
How do you read the data from an element?
elm.dataset.gooGoo
Where gooGoo is an attribute named “data-goo-goo” on the element.
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’);
How do you delete a data attribute using data-set?
delete dataset.fooFoo
Why is querySelector better than getElementById?
querySelector has a more robust selection mechanism and can use CSS selectors.
Why is querySelector worse than getElementById?
It’s not supported as widely (IE8 and above - although IE8 only has CSS 2.1 support).
What are the most common methods of selecting a DOM element?
document. querySelector(‘a’);
document. getElementById(‘myid’);
What is the most common method of selecting a list of nodes in a document?
document. querySelectorAll()
document. getElementsByTagName()
document. getElementsByClassName()
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.
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');
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.
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).
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
HTMLCollections contain elements in what order?
Document order, i.e. the order they appear in the document.
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
What datatype are most of the preconfigured legacy arrays (i.e. document.links)?
HTMLCollection interface / objects
What datatype is the document.stylesheets preconfigured array?
StyleSheetList
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.
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.
What is the CSSOM View Module?
An API that allows the modification of the visual representation within the browser of the DOM.
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.
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.
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
offsetHeight and offsetWidth include the width of the borders - how would you get this value without the border widths?
Use clientHeight and clientWidth
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)
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.
What properties give you the width and the height of the element being scrolled?
scrollWidth and scrollHeight
i.e.
document.body.scrollWidth
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
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.
How would you choose the tenth child element of a content element, and scroll it into view?
document.querySelector(‘content’).children[9].scrollIntoView(true);
What does the property ‘style’ return?
A CSSStyleDeclaration object
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.
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.
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
The CSSStyleDeclaration object also provides methods to change property values - what are they/
setPropertyValue()
getPropertyValue()
removeProperty()
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.
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.
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;’);
What is the equivalent of using cssText to get the style value?
div.getAttribute(‘style’);
How do you get the actual CSS for an element (including any from the cascade)?
getComputedStyle()
NOTE: This returns a read-only CSSStyleDeclaration
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.
Is the following valid?
window.getComputedStyle(div).backgroundColor = ‘red’;
No - the object returned by getComputedStyle is read only.
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.
Are textnodes created from whitespace?
Yes - if you place whitespace into the document, then you will get a textNode.
Are carriage returns considered textNodes?
Yes - since they are indeed whitespace.
What properties can be used to extract the text from a textNode?
data
nodeValue
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;
What methods can you use to remove / edit etc textNodes?
appendData() deleteData() insertData() replaceData() substringData()
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.
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.
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.
What function can you use to combine multiple textNodes?
document.querySelector(‘div’).normalize();
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.
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.
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.
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)
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.
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.
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.
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)
Each rule within a stylesheet is represented i n the DOM by a…
CSSStyleRule object
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]
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
How would you determine how many style sheets your document is making use of?
document.styleSheets.length
array starting at 0
Is styleSheets a live document?
Yes - like all Node Lists.
What is included in the styleSheets property?
All style sheets, both style element and link elements (where rel is set to stylesheet).
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.
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.
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
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).
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).
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).
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.
What kind of node does page inline javascript produce?
TextNode
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.
Should you use self closing Script tags?
No - only if you are doing XHTML
What are the optional attributes of the script tag?
charset, async, defer, src and type.
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.
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).
If you use defer on a script tag - when does the JavaScript actually get parsed?
Once the HTML node has been parsed.
What order are deferred scripts supposed to be executed?
According to the specification, document order - however, the actual adherence to this is spotty.
What kind of attribute is defer?
boolean
If you use defer - what javascript method is completely off the table?
document.write (as it can only write before the document is completed)
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.
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.
If you add defer and async attributes to a script tag - which one is used?
async
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.
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.
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() {});
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.
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.
Property event handler has historically been known as a…
DOM Level 0 event
addEventListener event handler has historically been known as…
DOM Level 2 event
Inline event handlers are sometimes known as…
HTML event handlers
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.
What are the different phases that occur when processing events?
Capture phase
Target phase
Bubbling phase
Which phase is the most commonly exploited of the event phases?
bubbling
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
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.
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.
Why might you choose to use bubbling over capturing?
Capturing is not available in IE9 and lower.
Why might you choose to use capture over bubbling?
In complex DOM’s bubbling is probably less efficient.
Why might event capturing be useful?
It allows you to intercept the message before it reaches the target.
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
Can the addEventListener method be used on XMLHttpRequest?
Yes
How do you remove an event listener?
Use removeEventListener
What is the gotcha with removing event listeners?
You can’t remove an event listener that was created with an anonymous function.
The value of ‘this’ inside an event listener is usually what?
The object the event is attached too.
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.
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.
How would you determine where an event originated from?
The event object passed to the event handler has a property called ‘target’.
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.
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”
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()
What is important to remember about preventDefault()?
The event itself is stopped, but the event still propagates (so my trigger other events elsewhere).
What is another way of preventing the default event occuring, other than using preventDefault?
You can return false at the end of the function.
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()
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.
Does stopImmediatePropagation stop default events occurring?
No, browser events will still occur.
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.
What is the parameter that you must send to document.createEvent
‘CustomEvent’
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.
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
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.
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’) {
}
Event delegation is idealy leveraged when we are dealing with event types such as…
click, mousedown, mouseup, keydown, keyup, and keypress