Lesson 08 DOM

Mark Harder, 09 November 2018

Modern Web Application Development

JavaScript and The DOM

The DOM Video


JavaScript (JS) is a programming language best known as the scripting language for Web pages. JavaScript can also run outside browsers on desktops and servers using Node.js

The standard for JavaScript is ECMAScript. As of 2012, all modern browsers fully support ECMAScript 5.1. Older browsers support at least ECMAScript 3. On June 17, 2015, ECMA International published the sixth major version of ECMAScript, which is officially called ECMAScript 2015, and was initially referred to as ECMAScript 6 or ES6. Since then, ECMAScript standards are on yearly release cycles.

We will be learning the JavaScript version knowns as ES6.

The Document Object Model (DOM)

The DOM is the interface between your JavaScript (programming code) and your HTML + CSS.

The DOM is a document model loaded in the browser and representing the document (HTML + CSS) as a node tree, where each node represents part of the document (e.g. an element, text string, or comment)

Lets start with a diagram to explain. DOM Image In JavaScript code we want to add the ability to select our HTML elements, read their contents, then make changes to them. Another way to explain the DOM is: The DOM programmatically describes your HTML and CSS page. The DOM represents the current state of the page, not the original file, this means that if code makes changes to the page, the DOM will reflect the current state instead, not the original file.

Lets walk through a demo to show javaScript and the DOM in action. Don’t think that you need to understand the details of the code we are going to show. The purpose of this demo is to teach the concept of the DOM.

The code for this section can be found on github. Please download the code and try it out on your machine. https://github.com/mhintegrity/lesson08

  1. Open the index.html file in Chrome Browser.
  2. Press F12 to open the Developer tools.
  3. Select the tab Console.
  4. Type in console.dir(document).
  5. Expand the carrots of #document to explore the DOM for the HTML page.
  6. Locate the head element, expand it and locate the title element.
  7. Locate the body element, expand and find the children object, expand again and find 0: h1.

Now lets look at the JavaScript in this project.

  1. In VS Code open the index.html page and look at the head section.
  2. You will see an entry like this <script defer src="main.js"></script>
    • script element tag tells the browser that this is JavaScript code. The attribute src points to an external file that contains JavaScript code.
    • the defer attribute tells the browser to wait till the HTML page and its DOM is loaded before loading and running the JavaScript file.
    • You can put your JavaScript code inside a script element, but we will be following the better practice of storing it in a separate file.
  3. Now open the main.js file in VS Code to look at.
  4. If you run the page and click on the button text “Hide the DOM image”, you will see the image disappear and the text of the button change to “Show the DOM image”.
  5. Now lets examine the JavaScript code that makes this happen.
    • The first line starts with // which indicates that this line is a comment only and not code.
       // Main JavaScript file used by index.html file //
    • Next line of code creates a variable (like in math where x holds stuff for us) named getButton
       let getButton = document.querySelector('#hide');
    • document is a reference to the page DOM
    • The period after document followed by querySelector is a reference to a function that document has. A function is like in math code/formulas that need to be run when referenced.
    • So document.querySelector() is code which acts similar to a selector part of a rule in CSS.
    • After a function name we use () parenthesis to contain any parameters (information the function need to work) we want to pass into the function.
    • document.querySelector(‘#hide’); works like a CSS rule, but returns only the first element (a button) with an id of hide from the DOM.
    • The next code line adds a listener to the button so that when the user clicks on the button, the function hideImage is called (run)
       getButton.addEventListener('click', hideImage.bind());
    • The bottom section is a custom function that we write.
       function hideImage(event) {
        if (document.getElementById('hide').innerText === 'Hide the DOM image')
            // Print a message inside the developer console.
            console.log("test Hide Image")
            // Like CSS we want to apply the display: none to our Image.
            document.getElementById('DOM').style.display = 'none';
            document.getElementById('hide').innerText = 'Show the DOM image'
            document.getElementById('DOM').style.display = 'block';
            document.getElementById('hide').innerText = 'Hide the DOM image'
    • We are not going to go into a lengthy explanation of this code yet, the purpose of this exercise is to show you the types of things we can do with JavaScript.

Intro to JavaScript

JavaScript Variables

JavaScript Code

A computer program is a list of instruction that are executed in order. Program instructions are called statements.

JavaScript statements are separated by semicolons ;

  • add a semicolon at the end of each executable statement:
      let x, y, z;    // Decalare 3 variables
      x = 3;          // Assign the number 3 to variable x
      y = 4;          // Assign the number 4 to variable y
      z = 3 + 4;      // Assign the sum of x and y to z;
  • Variables are memory containers used for storing data values Variables are much like variables in Algebra, except that they can contain data other than numbers.

  • 5 Primitive Data Types used in value variables
      // Numbers
      // Strings
      'What is your name'
      // Booleans
      // null and undefined
  • Like Algebra we can choose names for our variables;
      let namesShouldHaveMeaning = "Hello";
      let jesusIsLord = true;
  • Value = undefined
    • Variables are often initially declared without values. Until a variable has a value, it will have a value of undefined.
    • If you try to declare again the same variable you will get an error.
  • JavaScript algebra using operators and variables.
      let a = 4 + 3;
      let composeStr = "add strings" + " 4 + 3 = " + a;
      // "add string 4 + 3 = 7"

    JavaScript Arithmetic Operators

    Arithmetic operators are used to perform algebra on number data types

Operator Description Example
+ Addition x = x + y;
- Subtraction x = x - y;
* Multiplication x = x * y;
/ Division x = x / y;
% Modulus - Division Remainder x = x /y;
++ Increment by 1 x++;
-- Decrement by 1 x--;

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

Operator Example Same As
= x = y; x = y;
+= x += y; x = x + y;
-= x -= y; x = x - y;
*= x *= y; x = x * y;
/= x /= y; x = x / y;
%= x %= y; x = x % y;

JavaScript Comparison Operators

  • Comparison operators are used when comparing variables. For example we use it with IF statements.
Operator Description Example
== equal to if (5 == 5) { };
=== equal value and equal type if (a === b) { };
!= not equal if (a != b) { };
!== not equal value or not equal type if (a !== b) { };
> greater than if (a > b) { };
< less than if (a < b) { };
>= greater than or equal to if (a >= b) { };
<= less than or equal to if (a <= b) { };
? ternary operator
condition ? value if true : value if false
a = (5 >= 4) ? true : false;

Assignment due for discussion next class and NO check-in to GitHub.