Back to top

DOM

Back to top

Basics

The Document Object Model is the interface between your JavaScript and HTML & CSS.

Include JavaScript code at the bottom of HTML right before closing < /body> tag. Exceptions only if using a crazy large library that loads very slowly.

  • <script type="text/javascript" src="index.js" charset="utf-8"></script>

JavaScript uses the dot method and camel case document.querySelector("h1").style.fontSize = "100px";

CSS values need to use dot method, camel case, and as strings .style.fontSize = "100px";

Properties & Methods

Get Property

  • Tells you what the property is currently set to
    • h1.color; → black

Set Property

  • Sets the property to what you want to change it to
    • h1.style.color = "pink"; → "pink"

The difference between Get and Set is whether we set it equals to something or not

Call a Method

When the selected element does something. Ends in (): ie. - click(), setAttribute(), etc.

Methods and functions are very similar. The difference is that a method must be associated with an object

Process of Manipulating the DOM

Example: SELECT an element and then MANIPULATE

  • SELECT the <h1> and save to a variable
  • var h1 = document.querySelector("h1");
  • MANIPULATE using the <h1> we selected
  • h1.style.color = "pink";

Example: SELECT the <body> and change the background color every second

  • SELECT the <body>
  • var body = document.querySelector("body");
  • var isBlue = false;
  • MANIPULATE the element
  • setInterval ( function() {
     if (isBlue) {
       body.style.background = "white";
     } else {
      body.style.background = "#3498db";
     }
     isBlue = !isBlue;
    }, 1000);
  • 1000 mentioned above is in milliseconds: 1000 milliseconds = 1 second

DOM Selector Inputs

Code Reference for Following Examples:

  • <body>  <h1 class="italic">Hello</h1>
     <h1>Goodbye</h1>
     <ul>
      <li id="highlight"><a href="www.google.com">List Item 1</a></li>
      <li class="bolded italic">List Item 2</li>
      <li class="bolded">List Item 3</li>
     </ul>
    </body

getElementById

Takes a string argument and returns the one element with a matching ID. (Remember, you should only have one unique ID per document.)

  • document.getElementById("highlight").style.color = "yellow";
  • → Font color is then changed to yellow for List Item 1

getElementsByClassName

Takes a string argument and returns a list of elements that have a matching class

  • Returns an array, even if there is only one element
  • If you want to modify one element from the array (even if only one) you need to call it by number using square brackets
  • document.getElementsByClassName("bolded")[1].style.color = "red";
  • → Font color is then changed to red for List Item 3

getElementsByTagName

Returns a list of all elements of a given tag name, like < li> or < h1>

  • Returns an array, even if there is only one element
  • If you want to modify one element from the array (even if only one) you need to call it by number using square brackets
  • document.getElementsByTagName("li")[1].style.color = "purple";
  • → Font color is then changed to purple for List Item 2

querySelector

Returns the first element that matches a given CSS-style selector

Only returns the first matching element, even if there are many

  • SELECT by Tag
  • document.querySelectorAll("h1");
  • SELECT by Class Name
  • document.querySelector(".bolded");
  • SELECT by ID
  • document.querySelector("#highlight");
  • COMBINE SELECTORS
  • document.querySelector("li a");
  • → This one targets the a href inside of the li. This one needs a space between them because it is hierarchical.
  • COMBINE SELECTORS
  • document.querySelector("li.italic");
  • → This one targets only the li with the included class of italic. When the class is inside the same brackets as the li, you do not add a space between them.

querySelectorAll

Returns a list of elements that matches a given CSS-style selector

You can use all of the same options from above in: querySelector

Returns all of the matching elements in an array

  • Returns an array, even if there is only one element
  • If you want to modify one element from the array (even if only one) you need to call it by number using square brackets
  • document.querySelectorAll(".bolded")[1].style.color = "red";
  • → Font color is then changed to red for List Item 3

DOM Manipulation - Style

There are two main ways to manipulate style.

  1. Through direct commands using JavaScript in script tags (as shown in above examples)
  2. Through defining a CSS class and then toggling it on or off with JavaScript (as shown below)

1. Example: SELECT an element and then MANIPULATE

  • SELECT the id "highlight"
  • var tag = document.getElementById("highlight");
  • MANIPULATE by writing JavaScript inside script tags
  • <script>
    tag.style.color="blue";
    tag.style.border="10px solid red";
    tag.style.fontSize="70px";
    tag.style.background="yellow";
    tag.style.marginTop="200px";
    tag.style.display="none";
    </script>

2. Example: Define a CSS class and then toggle it on and off with JavaScript

  • DEFINE a class in CSS
  • .some-class {
     color: blue
     border: 10px solid purple;
    }
  • SELECT the element by ID
  • var tag = document.getElementById("highlight");
  • ADD the NEW CLASS to the SELECTED ELEMENT
  • tag.classList.add("some-class");

DOM Manipulation - classList

classList is a read-only list that contains the classes for a given element. It is not an array.

When adding, removing or toggling the class, do not use the dot in front of the class name inside of the parentheses

  • First, DEFINE a class in CSS
  • .another-class {
     color: purple
     fontSize: 76px;
    }
  • SELECT the element
  • var tag = document.querySelector("h1");
  • ADD the NEW CLASS to the SELECTED ELEMENT
  • tag.classList.add("another-class");
  • REMOVE a CLASS
  • tag.classList.remove("another-class");
  • TOGGLE a CLASS
  • tag.classList.toggle("another-class");
    • This switches on or off depending on what state it is currently in

DOM Manipulation - textContent

textContent returns a string of all of the text contained in a given element. This only includes text, and eliminates any styling tags you may have added to your HTML text that you are changing.

  • <p>This is an <strong>awesome</strong> paragraph.</p>
  • SELECT the <p> tag
  • var tag = document.querySelector("p");
  • RETRIEVE the textContent
  • tag.textContent; → This is an awesome paragraph.
  • ALTER the TEXT
  • tag.textContent=("blah blah blah");
    • If you change the text this way it loses all of the styling tags (ie - <strong></strong)

DOM Manipulation - innerHTML

innerHTML is similar to textContent, except it returns a string of all of the HTML contained in a given element. HTML includes all of the styling tags you have added to your text (< b>, < em>, etc.)

  • <p>This is an < strong>awesome</strong> paragraph.</p>
  • SELECT the <p> tag
  • var tag = document.querySelector("p");
  • RETRIEVE innerHTML
  • tag.innerHTML; → This is an <strong>awesome</strong> paragraph.
    • This keeps all of the styling tags (<strong></strong)

You can also add styling elements to your HTML when using this.

  • document.querySelector("h1").innerHTML = "<em>Hello</em>"

DOM Manipulation - Attributes

Use getAttribute() and setAttribute() to read and write attributes like or .

  • Example code:
  • <a href="www.google.com">I am a link</a>
  • <img src="logo.png">
  • Set variable
  • var link=document.querySelector("a");
  • getAttribute()
  • link.getAttribute("href"); → "www.google.com"
  • CHANGE the HREF attribute with setAttribute()
  • link.setAttribute("href", "www.cats.com");
    • → <a href="www.cats.com">I am a link</a>
    • ("href", "www.cats.com") First item is what you want to change, and the second one is what you want to change it to
  • CHANGE the IMAGE SRC with setAttribute()
  • var img=document.querySelector("img");

  • img.setAttribute("src", "tortiecat.png")
    • → <img src="tortiecat.png">

DOM Manipulation - Add New Div to Page

  • <script>
    var newElement = document.createElement("div");
    var addText = document.createTextNode("new text string");
    newElement.appendChild(addText);
    newContent = document.getElementById("title");
    document.body.insertBefore(newElement, newContent);
    }
    </script>
  • insertBefore(1, 2)
  • insertBefore 1. What you are adding
  • insertBefore 2. Where you are going to place it (this one is optional)

Advanced DOM Manipulation: DOM Events

DOM Events: Making Things Interactive

  • Examples of events:
    • Clicking on a button
    • Hovering over a link
    • Dragging and dropping
    • Pressing the enter key

The Process:

  • Select an event and then add an event listener
    • Listen for a click on this < button>
    • Listen for a hover event on the < h1>
    • Listen for a keypress event on text input
  • You can have more than one listener on an item

The Syntax

addEventListener method

  • element.addEventListener(type, functionToCall);
    • var button = document.querySelector("button");
    • button.addEventListener("click", function() {
       console.log("Someone clicked the button!");
      });

DOM Manipulation: Click Events

Responding to a Click

  • <p id="text">Hello World!</p>
    <button id="myButton">Change text</button>
    <script>
  •  document.getElementById("myButton").onclick = function() {
      alert("Button clicked!");
    }

alert("Button clicked!"); - Sets up the onclick script

Change text in response to a click

  • <p id="text">Hello World!</p>
    <button id="myButton">Change text</button>
    <script>
  • document.getElementById("myButton").onclick = function() {
     document.getElementById("text").innerHTML = ("Hi Katie!");
    }
    </script>

document.getElementById("text").innerHTML = ("Hi Katie"); This will change Hello World! to Hi Katie! after clicking the button

Add an event listener on click to all buttons with same class

  • let numOfDrumButtons = document.querySelectorAll(".drum");
    for (let i=0; i< numOfDrumButtons. length; i++) {
     buttons[i].addEventListener("click", function() {
      alert("I was clicked!");
     });
    }

DOM Manipulation: Changing Website Content

Add (Append) Content

Longer Version:

  • <p id="secondParagraph"></p>
  • <button id="secondButton">Append (add) text</button>
  • <script>
     document.getElementById("secondButton").onclick = function() {
     document.getElementById("secondParagraph").innerHTML =
     document.getElementById("secondParagraph").innerHTML + "awesome!";
    }
    </script>

Shorter Version:

  • <p id="secondParagraph"></p>
  • <button id="secondButton">Append (add) text</button>
  • <script>
     document.getElementById("secondButton").onclick = function() {
     document.getElementById("secondParagraph").innerHTML += "awesome!";
    }
    </script>

Add Text at Beginning & End

  • <script>
     document.getElementById("secondButton").onclick = function () {
     document.getElementById("secondParagraph").innerHTML = "I think " +
     document.getElementById("secondParagraph").innerHTML + "awesome!";
    }
    </script>

To Make Content Appear Out of Thin Air

This is a bit tricky. You will have to create an empty paragraph first that you will then change, therefore making it appear.

  • <p id="emptyPara"></p>
  • <button id="thirdButton">New Text</button>
  • <script>
    document.getElementById("thirdButton").onclick = function () {
     document.getElementById("emptyPara").innerHTML = "<h1>Hi there!</h1>";
    }
    </script>

Higher Order Functions

Higher order functions are functions that can take other functions as inputs

Examples:

1. Display a message when a button is clicked with an anonymous function

<button>Click Me</button>


<p>No One Has Clicked Me Yet</p>

  • var button = document.querySelector("button");
  • var para = document.querySelector("p");
  • SETUP EVENT LISTENER
  • button.addEventListener("click", function() {
     para.textContent = "Someone Clicked the Button!";
    });
    • The function() is the callback function. This one is anonymous (unnamed).
  • SHORTER VERSION OF ABOVE CODE
  • document.querySelector("ul").addEventListener("click", function() {
     console.log("You clicked the UL!");
    });

2. Rewrite previous example using a named function (instead of an anonymous function)

  • var button = document.querySelector("button");
  • var para = document.querySelector("p");
  • SETUP EVENT LISTENER
  • button.addEventListener("click", changeText);
  • function changeText() {
     para.textContent = "Someone Clicked the Button";
    }

3. Add Separate Listener for all li's within a ul

  • var lis = document.querySelectorAll("li");
  • for (var i = 0; i < lis.length; i++) {
     lis[i].addEventListener("click", function() {
      this.style.color = "purple";
     });
    };
    • this refers to the item that was clicked on, hovered over, etc.

4. Add Separate Listeners for all 7 buttons on a page (example from Drum Kit)

  • var buttons = document.querySelectorAll(".drum");
  • var totalNumberOfButtons = document.querySelectorAll(".drum").length;
  • for (var i = 0; i < totalNumberofButtons; i++) {
     buttons[i].addEventListener("click", function() {
      alert("I've been clicked!");
     });
    };

this Keyword

MDN Docs: this Keyword

W3Schools: JavaScript this Keyword

Lots of different ways to use the this keyword. Refer to docs above for more instances.

For our sake, this refers to item that had an event listener and was waiting for something to happen. this now refers to the item that was clicked, hovered over, etc.

Examples:

1. In this example, this will console log the button that was pressed. (From Drum Kit project)

  • document.querySelectorAll(".drum").addEventListener("click", function() {
     console.log(this);
    });

2. Or use console.log(this.innerHTML); and it will console.log the text of that button

3. Use this keyword and change code so that when you click the text color will change to white

  • document.querySelectorAll(".drum").addEventListener("click", function() {
     this.style.color = "white";
    });

Keyboard Event Listeners

W3Schools: Keyboard Events

When you interact with the keyboard, the keyboard events are fired. There are two main keyboard events.

  1. keydown - fires when you press a key on the keyboard and it fires repeatedly while you are holding down the key
  2. keyup - fires when you release a key on the keyboard
  3. keypress - NOW DEPRECATED - Use keydown instead.

When you press a character key once on the keyboard, the two keyboard events are fired in the following order:

  1. keydown
  2. keyup

The keydown event is fired before any changes were made to the text box, whereas the keyup event fires after the changes have been made to the text box. If you hold down a character key, the keydown is fired repeatedly until you release the key.

When you press a non-character key, the keydown event is fired first followed by the keyup event. If you hold down the non-character key, the keydown is fired repeatedly unil you release the key.

Syntax for Keyboard Event Listeners

MDN Docs: DOM Events List for Reference

Event listeners are always named in all lowercase (keydown, etc.). Check above reference for correct name and spelling

Syntax example:

  • document.addEventListener("keydown", function() {
     alert("Key was pressed");
    });
  • In the above example, there is an anonymous function that just listens to any keydown pressed on any key on the keyboard. Any keydown triggers the alert.
  • But, if you want something to happen when a specific key is pressed, you can write a function and pass it in as a parameter to the anonymous function.

Example:

  • <p>Press keys on the keyboard to see what the KeyboardEvent's key and code values are for each one.</p>
    <div id="output"></div>

    <script>
    window.addEventListener("keydown", function(event) {
    let str = "KeyboardEvent: key='" + event.key + "' | code='" + event.code + "'";

    let el = document.createElement("span");
    el.innerHTML = str + "";

    document.getElementById("output").appendChild(el);
    }, true);
    </script>

Press keys on the keyboard to see what the KeyboardEvent's key and code values are for each one.

>

Callback Functions

MDN Docs: Callback Function Definition with Example

Codeburst.io: JavaScript: What the heck is a Callback?

Freecodecamp: What is a Callback Function in JavaScript?

Freecodecamp: JavaScript Callback Functions: What are Callbacks and How to Use Them

Why Do We Need Callback Functions?

JavaScript runs code sequentially in top-down order. However, there are are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.

Callbacks make sure that a function is not going to run before a task is completed, but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed.

Side Note: Higher-Order-Functions accept other functions as a parameter. Callback functions are the ones placed as the parameter.

Example:

In this example the setTimeout function will call the function after 3 seconds (3000 milliseconds). In other words, the message function is being called after something happened (3 seconds passed), but not before. So this is an example of a callback function.

  • const message = function() {
     console.log("This message is shown after 3 seconds");
    }

    setTimeout(message, 3000);

Alternative Example:

We can define a function directly inside another function, instead of calling it. In this one the callback function has no name, and therefore is an anonymous function.

  • setTimeout(function() {
     console.log("This message is shown after 3 seconds");
    }, 3000);

Callback Functions for Event Declarations

JavaScript is an event-driven programming language. We also use callback functions for event declarations. For example, let's say we want users to click on a button:

<button id="callback-btn">Click here</button>

This time we will see a message on the console only when the user clicks on the button:

  • document.querySelector('#callback-btn').addEventListener("click", function() {
      console.log("User has clicked the button");
    });

Here we first select the button with its id, and then we add an event listener with the addEventListener method, which takes two parameters. The first one is its type, "click", and the second parameter is a callback function, which logs the message when the button is clicked.

How to Toggle Hiding & Showing An Element

Toggle between hiding and showing an element with JavaScript

In this case, the element is already visible. If it is hidden to start, switch the order of block and none in the if statement.

1. Add HTML

  • <button id="buttonIdName">Click to Toggle</button>
  • <div id="myDiv">
     This is my Div Element.
    </div>

Add JavaScript

  • function toggleFunction() {
     var x = document.getElementById("myDiv");
     if (x.style.display === "none") {
      x.style.display = "block");
     } else {
      x.style.display = "none";
     }
    }

Coding Challenges

Challenge: Select the third li and change the text to your name

  • <body>
     <h1>Hello</h1>
     <input type="checkbox">
     <button style=":active color:red;">Click Me</button>
     <ul>
      <li class="list"><a href="https://www.google.com">Google</a></li>
      <li class="list">Second</li>
      <li class="list">Third</li>
     </ul>
    </body>


  • document.querySelector(".list:nth-child(3)").innerHTML=("Katie")


Challenge: Create a simple calculator that can add, subtract, multiply and divide two numbers

Hint: Use a higher order function (a function within a function).


  • function add(num1, num2) {
     return num1 + num2;
    }
    function subtract(num1, num2) {
     return num1 - num2;
    }
    function multiply(num1, num2) {
     return num1 * num2;
    }
    function divide(num1, num2){
     return num1 / num2;
    }
    function calculator(num1, num2, operator) {
     return operator(num1, num2);
    }
  • Then you have to call the function and add in your parameters to make it work
  • calculator(4,5,multiply)


Challenge: Disappearing Circles

Set up a red, blue, and yellow circle. Use JavaScript so each one will disappear when clicked.


3 Divs set with ID's in HTML

  • <div id="blue"></div>
    <div id="red"></div>
    <div id="yellow"></div>

CSS to create circles

  • #blue {
    background: blue;
    border-radius: 50%;
    width: 300px;
    height: 300px;
    }

    #red {
    background: red;
    border-radius: 50%;
    width: 300px;
    height: 300px;
    }

    #yellow {
    background: yellow;
    border-radius: 50%;
    width: 300px;
    height: 300px;

    }

JavaScript

  • <script type="text/javascript">
     document.getElementById("blue").onclick = function() {
      document.getElementById("blue").style.display = "none";
     }

     document.getElementById("red").onclick = function() {
      document.getElementById("red").style.display = "none";
     }

     document.getElementById("yellow").onclick = function() {
      document.getElementById("yellow").style.display = "none";
     }
    </script>