DOM Hands On

Dr. Greg Bernstein

Updated February 21st, 2021

DOM Hands On

Learning Objectives

  • Understand why and how we select elements on a page
  • Remember how we can modify element content on a page
  • Remember why and how we create elements and add them to a page
  • Remember why and how to respond to events from elements

Selecting Elements: Why

We need to “grab” DOM elements in JavaScript so we can:

  • Change element content (innerHTML, outerHTML)
  • Add new elements (appendChild, etc)
  • Add event listeners (addEventListener(event, callback))
  • Get values, ids, and other element information

Selecting a Single Element

  • document.querySelector(selString), element.querySelector(selString) where element is any element from the page. This returns first element to match CSS like selString

  • document.getElementById(idString)

Selecting Multiple Elements

  • document.querySelectorAll(selString) – I only use this
  • document.getElementsByClassName(classString)
  • document.getElementsByTagName(tagString)

Example Page

DOMPracticeStates.html

<body>
    <main>
        <header>
            <h1 id="PageTitle">DOM and Array Practice with US state data</h1>
        </header>
        <section id="IntroSection">
            <h2>JavaScript DOM and Array Practice</h2>
            <p> This page includes an JavaScript array of objects about states in the US. You will use this data to create DOM elements per the homework instructions.
            </p>
            <p>You are not allowed to modify the HTML, only the script tag at the bottom of the body.
            </p>
        </section>
        <section id="LastAdmit">
            <h2>The Last Five Admitted States</h2>
            <ol></ol>
        </section>
        <section id="FavState">
            <h2>Favorite State Contest</h2>
            <form>
                <label>Your Name</label><input type="text" placeholder="name">
                <label>Favorite State</label>
                <select>
                    <option>California</option>
                    <option>Hawaii</option>
                    <option>Oregon</option>
                    <option>Washington</option>
                </select>
                <button>Add Info</button>
            </form>
            <p class="result"></p>
        </section>
        <section id="CapGame">
            <h2>Learn Your State Capitals</h2>
            <button>Change State</button>
            <div></div>
        </section>
    </main>
    <script>
        /* Your code here */
    </script>
</body>

Changing Content Example 1

Grab the element then use element.innerHTML = "new content";

// Example change the content of the first h1 on the practice page
var myh1 = document.querySelector("h1");
myh1.innerHTML = "Good Morning Class!";

Changing Content Example 2

Grab the element then use element.outerHTML = "<tag>new content</tag>";

// Example change the content of the h2 in the "CapGame" section to an h3.
var capGameh2 = document.querySelector("#CapGame h2");
capGameh2.outerHTML = "<h3>Yes you can do this!</h3>";

JavaScript Arrays: Sorting

Find the last admitted states

function admitOrder(stateA, stateB) {
    return stateB.admission_number - stateA.admission_number;
}
states.sort(admitOrder);

JavaScript Arrays: Slice

Find the last five admitted states

var lastFive = states.slice(0,5); // Produces a shallow copy

Create Elements

Add the last five states as list items

var stateList = document.querySelector("#LastAdmit ol");
function createStateItem(state) {
    let stateLi = document.createElement("li"); // Need to create new thing
    let content = `<p>${state.state} was admitted to the union ${state.admission_date}</p>`
    content += `<p>${state.code} is known as the ${state.nickname}</p>`
    stateLi.innerHTML = content; // set the content
    stateList.appendChild(stateLi); // add to parent element
}
lastFive.forEach(createStateItem); // Use method for each state

Listening for Events

Listen for button click on capital game section

favButton = document.querySelector("#FavState form button");
function tempHandler(event) {
    event.preventDefault(); // needed since I don't want default form behavior
    console.log("You click the button!");
}
favButton.addEventListener("click", tempHandler);

Grab Values and Do Something

// Grabbing elements I need from page
result = document.querySelector("#FavState p.result");
userName = document.querySelector("#FavState form input");
select = document.querySelector("#FavState form select");
// Create event handler
function buttonHandler(event) {
    let p = document.createElement("p");
    // Just getting values from input and select components
    p.innerHTML = `${userName.value} selected ${select.value}`;
    result.appendChild(p);
}
favButton.addEventListener("click", buttonHandler);
// reveal.js plugins