Introduction to JavaScript III - Intro to DOM Manipulation

Learning Goals

  • Continue to learn how to access and use the Chrome Developer Tools
  • Continue to develop a basic understanding for JavaScript syntax
  • Understand how to query and update a page after its been loaded

Vocab

  • HTML Element A building block that makes up the structure of a web page.
  • CSS Selector A way to identify a set elements, typically using a tag, class or id.
  • Interface a shared boundary across which two separate components exchange information.
  • DOM Document Object Model, the JS interface used to interact with HTML
  • Event Any event which takes place in the DOM, these can be generated by users or the browser.
  • EventHandler A function that will run when a specific event occurs

The Document Object Model (DOM)

DOM Documentation

The browser gives us some useful global objects for free. The window object is the global object and it holds a lot of information about the browser window including it’s current location (URL), size, etc. document contains a representation of the current web page.

document contains a bunch of methods that allow us to query the DOM. Let’s talk about two commonly used methods.

document.querySelector();
document.querySelectorAll();

Both methods take a query selector—like you would use in CSS. document.querySelector() returns the first element that matches the query. document.querySelectorAll() returns a collection of all the elements that match the query.

Let’s say we have a page with the following markup:

See the Pen Simple HTML Page by Turing School of Software and Design (@turing) on CodePen.

Let’s try out some queries:

  • document.querySelectorAll('p') will return a collection containing all of the paragraphs.
  • document.querySelector('p') will return just the first paragraph.
  • document.querySelector('#third') will return the paragraph with the id third.
  • document.querySelectorAll('.awesome') will return a collection containing the two paragraphs with the class awesome.

For today’s lesson, we will only be working with document.querySelector(). We will focus on how to best utilize document.querySelectorAll() once we learn more about arrays and loops!

Updating our HTML

Elements have a number of useful properties and methods.

Let’s say we wanted to change the contents of our <h1> element. We could modify it’s contents with the following JavaScript.

var h1Element = document.querySelector('h1');

h1Element.innerText = 'JavaScript is amazing!';

See the Pen Simple HTML Page (Now with JavaScript!) by Turing School of Software and Design (@turing) on CodePen.

The DOM has been updated to the following:

<h1>JavaScript is amazing!</h1>

<p>The is the first paragraph.</p>
<p class="awesome">The is the second paragraph.</p>
<p id="third" class="awesome">The is the third paragraph.</p>

Your Turn

  • Grab the first paragraph element and change the text to ‘The original paragraph’.

.innerText vs .innerHTML vs .textContent

<!-- The following line of HTML will be used in the next side track example -->
<!-- Note the extra spaces after hello - that is intentional -->
<p id="inner-text-example">Hello    <span>1906</span></p>

Side Track: You may have heard about a few different ways to target/manipulate the text of an HTML page. The two most common are innerText and innerHTML, with a third being textContent. The first answer in this convo gives you a quick answer, but if you’re curious run the following few lines of code in your console:

var para = document.querySelector('#inner-text-example');
console.log(para.innerText);
console.log(para.innerHTML);
console.log(para.textContent);

MDN has a great description of the differences between innerHTML, innerText, and textContent

To sum up:

  • innerText will collapse all of the extra spaces and give you back JUST THE TEXT.
  • innerHTML will give you back the text, with any nested HTML elements printed out as well
  • textContent will give you back an exact copy of JUST THE TEXT, leaving any spacing or formatting as is.

Pair Practice

Visit this page and fork the CodePen.

See the Pen HTML Report Card by eric weissman (@eric_turing) on CodePen.

Beginning

  • Find the h1 tag and change the header to “A Stellar Record of My Performance”.
  • Find the element with the class of hs and capitalize it’s name.
  • Change the subject of each of the elements with the ids of math, science, and language-arts.
  • Find the element with the id of message and change the message to something warm and uplifting. Do the same with element with an id of status!

Intermediate

  • Add a button called Change Name. Find all of the elements with a class of student and change them to your name when the button is clicked!
  • Add a button called Change Grades. Find all of the elements with the class of grade. Iterate through all of them and change their content to A+s when the button is clicked.
  • Can you create a function that takes an HTML element as an argument and capitalizes its contents?

Challenging

  • Select an element and set contentEditable to true. Now, click on the element. What happened?
  • Take a look at the MDN documentation for DOM events. Can you bind a function to the click event of the element?

Adding Event Listeners

Changing stuff on the page with JavaScript is all well and good, but if you might as well have just written it in the markup to begin with. The real power of JavaScript comes into play when we write code that responds to user input.

The real power of using JavaScript to change pages emerges when we start listening for user events.

This is the crux of front-end engineering. We present a user interface and then as the user interacts with the UI, we change and update what they see.

Let’s take a look at the syntax and then we’ll talk about what’s happening.

See the Pen A First Event Listener by Turing School of Software and Design (@turing) on CodePen.

  1. We’re querying for all of the elements we need and we’re storing them in variables.
  2. We’re adding an event listener to the <button> with the class of .change-text.
  3. We’re passing addEventListener() two arguments:
    • The type of event we’re interested in listening for.
    • A function that should be called whenever that event happens.

Pair Practice

  • Create a function called changeMessage that executes the code you wrote for updating the element with a class of message
  • Add a <button> to the HTML markup of the page.
  • Add an event listener to that button.
  • When the button is clicked, have your changeMessage function fire!

Extensions

Here is MDN’s master list of DOM events. Most of them are rare birds. Can you add additional events to the page?

If that list overwhelms you, here is a artisanal, hand-crafted list:

  • mouseenter
  • mouseleave
  • dblclick
  • keydown
  • keyup

Changing Styles Programmatically

We can also modify the CSS styling of any element on the page using JavaScript.

There are three approaches:

  1. We can directly manipulate the style of the element through inline styles.
  2. We can add or remove classes from the element (the preferred way).
  3. You can modify the stylesheet itself with JavaScript.

We’re only going to talk about the first two today.

Consider the following:

See the Pen CSS Manipulation with JavaScript by Turing School of Software and Design (@turing) on CodePen.

Pair Practice

  1. Add a button that changes the width of the box to 400px.
  2. Add a button that removes the border class from the box. (Hint: the method is called remove instead of add.)

Getting User Input from Forms

To access the value from an input element we can do the following

See the Pen Color Box - Get Color by Nathaniel Foster (@nfosterky) on CodePen.

Let’s use this pen for practice

See the Pen Color Box by eric weissman (@eric_turing) on CodePen.

Pair Practice

  • Add an input field with the id of “very-important-message” along with a button. When the user clicks on the button, it should set the innerText of the box to contents of the input field.
  • Add two inputs one for a CSS property and one for a value. When the user clicks the button, it should adjust that property on the box.
  • Here is an example of the second task:

Custom CSS Color Box

  • When the button is clicked, one of your JavaScript functions from the previous session should execute (such as updating all of the grades).

Summary

  • What is the DOM?
  • How do we get information out of the DOM and into our JS?
  • How do we add information to the DOM?
  • How can we change the CSS of elements?
  • What is the preferred method for updating our CSS using JS?

Lesson Search Results

Showing top 10 results