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