Saturday, June 4, 2016

Talking DOMball...

Hello all you baseball fans and JS wahoos, it's time for another season of baseball!!
It's also time for us to discuss the differences between two similar sounding words in Javascript, document, and window.

window is the global object in Javascript. It holds everything, like global variables, global functions, history, location, etc. Global functions, such as setTimeout and console, live on the window as well.  Even document lives on the window.

console.log(window.setTimeout === setTimeout); // true
console.log(window.document === document); //true

window can also be thought of as the default scope or this keybinding in browser-based JS (environments like nodejs do not have a window object).

var x = 5; //x in global/window scope
console.log(this.x === window.x); //true

console.log(this === window); //true

document is the DOM. The DOM is a tree of nodes (html tags, like h1, div, span, etc), and may be thought of as an object-oriented representation of the HTML that makes up the page. For an example of what this tree looks like, check out this site:

https://gojs.net/latest/samples/DOMTree.html

document is immensely useful because it allows us to query and manipulate the DOM using Javascript. For example, to grab all h1 elements in the DOM, we would write:

var headers = document.getElementsByTagName('h1');

Check back later, when we'll continue our exploration of window and document.

1 comment:

  1. allintext:"DOM JavaScript" "powered by blogger"
    JavaScript is the language future. The new JavaScript Version (Ecmascript 6) has been relaeased.

    JavaScript Online Training

    Javascript Online Training

    ReplyDelete