Introduction to the

DOM

dom-dom-dommmm

Objectives

  • define what the DOM is
  • draw out a DOM tree
  • get an element in the DOM
  • modify an element in the DOM
  • handle a user event
  • create an element
  • insert an element into the DOM

What is the DOM?

Research what is the DOM using google

Turn and talk to discuss what you found

Map out the DOM in tree form

Get an element from the DOM

The browsers provide the document object for us

'use strict';

let title = document.getElementById('title');

let titleText = title.textContent;

console.log(titleText);

Check out the contents of the title object!

console.log('title');
console.dir('title');

Modify an element in the DOM

We can use the object that we had previously retrieved

'use strict';

let title = document.getElementById('title');

title.textContent = 'Hello World!';

.textContent is not the only property that we can modify the title object

title.innerHTML = 'Hello World!';

Search for 

"mdn dom element"

Handling the users

Those pesky users keep on expecting things to happen when they click on things

'use strict';

let title = document.getElementById('title');

title.addEventListener('click', () => {
  console.log('I was clicked!');
});

There are many other events that can be fired! Look them up on mdn with the search terms

"mdn event list"

Creating an element

The real power is in creating our own elements in JavaScript.

'use strict';

let newItem = document.createElement('li');

newItem.textContent = 'I am a new item!';

Inserting the element into the DOM

Just creating the element is nice and all, but it would be nicer if it made its way onto the screen

'use strict';

let list = document.getElementById('list');

let newItem = document.createElement('li');

newItem.textContent = 'I am a new item!';

list.appendChild(newItem);

There are other methods to add an element to the screen. Look them up on MDN

Exercise

  • Create a basic empty HTML page
  • Link a JavaScript file
  • Using only JavaScript
    • Add a H1 title to the page
    • Add a list of your favorite animals
    • Add an event handler to log what animal was clicked to the console

Stretch

  • Create an array of foods
  • For each food item
    • Create an list element
    • Add the food to the element
    • Insert the element into the DOM

intro_to_the_DOM

By Brooks Patton

intro_to_the_DOM

This slide deck is for introducing the student to the DOM.

  • 1,079