JS201: JS and the DOM (Review)


Slides: http://www.teaching-materials.org/jsdom

What is the DOM?

"Document Object Model"

Terminology


  • The DOM, just like JavaScript objects, is a data structure called a "tree"
  • Each point of data is called a "node"
  • Each "node" can have a "parent", "child", and/or "sibling" nodes
  • The DOM is accessed by a global variable called document
  • We can also use "dot notation" to access methods and properties

Try it!


Work with a buddy. Look at the image and code on the next slide and take turns identifying each of the following:


parent + child sibling + sibling node tag attribute
<html>
    <head>
        <title>My page</title>
    </head>
    <body>
        <h1>This is a header - the biggest one</h1>
        <p>This is a paragraph</p>
        <ul>
            <li>This is a list item</li>
            <li>And here is another</li>
            <li>Fish</li>
        </ul>
        <div class="catbox">
            <img src="http://placekitten.com/300/300" id="ms_von_cuten">
            <p>Ms Von Cuten</p>
        </div>
        <div class="catbox">
            <img src="http://placekitten.com/200/400" id="mr_snuggles">
            <p>Mister Snuggles </p>
        </div>
        <div class="catbox">
            <img src="http://placekitten.com/300/500" id="professor_buttonsworth">
            <p>Professor Buttonsworth</p>
        </div>
    </body>
</html>


  

One simple way to visualize it...

document = {
  head: {
    children: [ ] //returns child nodes
  },
  body: {
    classList: ['reveal'],
    hasChildNodes: function() {
      //returns true or false
    }
  },
  querySelectorAll: function(arg) {
    //returns matching node list
  }
}
  

Because the document is an object, we can access properties and methods with "dot notation".

Try it!


Open your JS console and try these...

document.body
document.body.children
document.querySelectorAll('section')

Can you find any other methods and properties this way?

Traversing the DOM


Sometimes we need to find the right node

  • animate
  • react/listen
  • get/set data

Selecting a list of nodes


by selector

document.querySelectorAll('section h2');

by tag name

document.getElementsByTagName('div');

by class name

document.getElementsByClassName('upper');

Selecting a single node


by ID

document.getElementById('section');

by selector

document.querySelectorAll('section h2')[3];

by tag name

document.getElementsByTagName('p')[9];

by class name

document.getElementsByClassName('upper')[0];

Try it!

  • In your browser, navigate to https://twitter.com/gdisf
  • Work with a buddy. One person will verbally call out an element on the page. The other will select it using the JS console. Take turns switching!
  • You will know you got it right when you hover over the element in the console and the element highlights on the page.

Creating a node

Three step process


Create and store

var myNewElement = document.createElement('div');

Edit

myNewElement.innerHTML = 'I am the html inside of a <em>brand new</em> div tag!';
myNewElement.className = 'new';

Insert

document.body.appendChild(myNewElement);

Try it!

Using the Developer Tools Console, create an <img> tag and store it. Give it an src attribute with an image of your choice. Finally, append it to this slide!

Events and their Callbacks

Terminology


  • Event: something that happens
  • Callback: a function that executes after the event has happened
  • Event listener: a method that binds an event to a callback

A basic example

Try this in your console

var myButton = document.querySelectorAll('button#testButton')[0];

myButton.addEventListener('click', function() {
  console.log('button clicked!');
});

Try it!


In your console, update the last event listener and callback so that it logs a count of how many times the button has been clicked.

Anonymous functions


Example:

var myButton = document.querySelectorAll('button#testButton')[0];

myButton.addEventListener('click', function() {
  console.log('button clicked!');
});

The callback cannot be removed, because we don't have a reference to it.

Referenced functions

Example:

var myButton = document.querySelectorAll('button#testButton')[0];

//store and define the function
var myCallback = function() {
  console.log('button clicked!');
};

myButton.addEventListener('click', myCallback);

The callback can be removed, since we have a reference.

myButton.removeEventListener('click', myCallback)

What about my arguments?


Arguments like the Event Object get applied to the callback:

var myButton = document.querySelectorAll('button#testButton')[0];

//store and define the function
var myCallback = function(e) {
  console.log(e); //logs the Event object
};

//no argument needed for binding the event
myButton.addEventListener('click', myCallback);

Final Exercise


Appendix

Advanced Features of Functions

How do arguments get applied?


Part 1: arguments array

Each JavaScript function has an arguments array, regardless of how you define it.

// notice no arguments here
var myFunc1 = function() {
  console.log(arguments);
}

// one argument here
var myFunc2 = function(e) {
  console.log(e);
  console.log(arguments);
}

myFunc1('abc', 123); // logs ['abc', 123]

myFunc2({Event: 'click'}, false); // notice extraneous argument
// logs {Event: 'click'}
// then logs [{Event: 'click'}, false]

How do arguments get applied?


Part 2: .apply()

Each JavaScript function has a method .apply(), which calls a function with a specified scope and arguments array.

var myCallback = function(e) {
  console.log(e);
}

var myEventListener = function() {
  myCallback.apply(this, arguments);
}

myEventListener('Wow, look at this string get applied as an argument to myCallback!')