Instructor: Dan Muzyka
danmuzyka.ai@gmail.com
In browsers, the window object is used as the JavaScript global object.
var hansel = {
firstName: "Hansel",
age: 8,
favoriteFood: "gingerbread"
};
window.gretel = {
firstName: "Gretel",
age: 8,
favoriteFood: "jelly beans"
};
console.dir(window.hansel);
console.dir(gretel);
The document object represents the HTML document inside the window. It is a child of the window object.
console.log(window.document === document); // true
The document is comprised of nodes, which correspond with the HTML tags and text in the document. The root <html> element is represented by the documentElement property of document.
console.log(document.documentElement);
A high-level representation of the document node tree looks something like this:
You can traverse the DOM tree using the childNodes and parentNode properties of a node.
console.dir(document.childNodes);
console.dir(document.body.childNodes);
console.log(document.body.parentNode);
console.log(document.body.childNodes[1].parentNode === document.body);
Other ways to traverse the DOM tree: firstChild, lastChild, nextSibling, previousSibling.
console.log(document.body.childNodes[1] === document.body.firstChild.nextSibling);
console.log(document.body.lastChild === document.body.childNodes[document.body.childNodes.length - 1]);
Other node properties: nodeType. An integer representing the type of node. Important values are:
ELEMENT_NODE | 1 |
TEXT_NODE | 3 |
DOCUMENT_NODE | 9 |
DOCUMENT_TYPE_NODE | 10 |
DOCUMENT_FRAGMENT_NODE |
11 |
console.log(document.nodeType);
console.log(document.body.nodeType);
console.log(document.documentElement.previousSibling.nodeType);
Other node properties: nodeName. A string, either the name of the tag in all caps (if the node is an element node), or '#text' for a text node, or '#document' for the document node.
console.log(document.nodeName); // #document
console.log(document.body.nodeName); // BODY
console.log(document.head.childNodes[0].nodeName); // #text
Other node properties: nodeValue. For text nodes, the value of the text. For most other node types, null.
You can access more specific DOM nodes directly.
var contentDiv = document.getElementById('content'),
paragraphs = contentDiv.getElementsByTagName('p'),
firstLink = paragraphs.querySelector('a'), // querySelector and
// querySelectorAll work
allLinks = paragraphs.querySelectorAll('a'); // on modern browsers,
// including IE 8+
DOM methods are expensive, so a good pattern is to use them as little as possible by storing the results in a variable.
// antipattern
for (var i = 0; i < 100; i += 1) {
document.getElementById("result").innerHTML += i + ", ";
}
// better - update a local variable
var i, content = "";
for (i = 0; i < 100; i += 1) {
content += i + ",";
}
document.getElementById("result").innerHTML += content;
// Stefanov, Stoyan. JavaScript patterns. Sebastopol, CA: O'Reilly, 2010.
The previous examples were for accessing the DOM. You can also manipulate the DOM.
var newParagraph = document.createElement('p'),
newText = document.createTextNode('Hansel and Gretel left a breadcrumb trail...'),
newDiv = document.createElement('div'),
otherParagraph = document.createElement('p'),
otherText = document.createTextNode('Hansel shoved the witch into the oven...');
newParagraph.appendChild(newText);
otherParagraph.appendChild(otherText);
newDiv.appendChild(otherParagraph);
newDiv.insertBefore(newParagraph, otherParagraph);
document.body.appendChild(newDiv);
Again, it is better to minimize DOM access by copying the DOM nodes into a variable, manipulating the variable, and then inserting the results back into the DOM.
var p, t, frag;
frag = document.createDocumentFragment();
p = document.createElement('p');
t = document.createTextNode('first paragraph');
p.appendChild(t);
frag.appendChild(p);
p = document.createElement('p');
t = document.createTextNode('second paragraph');
p.appendChild(t);
frag.appendChild(p);
document.body.appendChild(frag);
// Stefanov, Stoyan. JavaScript patterns. Sebastopol, CA: O'Reilly, 2010.
Useful reference for available DOM properties and methods:
Examples of browser events include mouse events and keyboard events.
Like example 1, but should add the following, and is attached to a parent node of the intended event target.
// get event and source element
e = e || window.event;
src = e.target || e.srcElement;
if (src.nodeName.toLowerCase() !== "button") {
return;
}
http://www.jspatterns.com/book/8/click-delegate.htmlJavaScript can make HTTP requests back to the server using an XMLHttpRequest object.
var xhr = new XMLHttpRequest();
// When the xhr object's readyState is 4, we have a response ready.
// Need to set up an event handler callback to respond to that
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// Handle ajax response
}
}
// Make the request.
// first parameter is HTTP method, second is URL,
// final is boolean indicating whether asynchronous or not
xhr.open("GET", "page.html", true);
// If you use POST method, you can pass post data in send()
xhr.send("");
Finish your midterm presentation. See https://github.com/aipdx-wdim387/week4 for details.