Intro to DOM Manipulation
đŻ Learning Goals
- Use the console in the Chrome Developer Tools
- Query and update a page after its been loaded
- Respond to user interactions with event listeners
đ Technical Vocabulary
- CSS Selector
- DOM (Document Object Model)
- Event
- Event Handler
- Event Listener
- HTML Element
- jQuery
- library
đ Warm Up
In order to work all the way through this lesson, we will need to learn how to use the Chrome Developer Tools (aka Dev Tools). Weâve used the console in repl quite a bit up until now; the Chrome Dev Tools are a more sophisticated version of that!
Like a true developer, you are going to take some time to do some research to teach yourself how to use this tool. Below are three resources, but feel free to find your own great resources as well!
- This short screencast was made just for you!
- Here is a tutorial on how to open the Dev Tools
- Here is a video on how to use a console.log
- Here is a blog post on how to use console.log (You can stop reading when you get to the
debugger
section)
What is the DOM?
The DOM, or Document Object Model, represents how the browser reads HTML. It allows JavaScript to interact with your HTML, which ultimately lets us manipulate, structure, and style our websites.
Manipulating the DOM refers to changes that are made in the browser, which are prompted but not directly created by the user.
Hereâs a real-life example of DOM Manipulation:
If I type my email in a form, then click âSubmit,â I might see a message like âThanks for signing up!â
I clicked the button, and in response, JavaScript made that message appear. In this lesson, we will learn how to change something on our site based on user interaction.
đ Brainstorm
Visit your favorite site. Write a list of at least 3 places you think the developers used DOM manipulation. Be ready to share!
jQuery
There is a popular library, or chunk of code someone else wrote, called jQuery. There are a lot of things it can do, all of which are still JavaScript, but itâs less for us to write! When using it, itâs essential that the HTML script tag below is included inside of the head
element in HTML. Any starter kit will already include this!
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
During camp, we will use jQuery anytime we want to write code that interacts with elements on the DOM. Keep in mind that when we use features of jQuery, we are still writing JavaScript. Itâs just a little âextraâ on top!
Access Elements from the DOM
Accessing elements is the first step in building out the functionality to respond to user input. By the end of this lesson, youâll be able to let a user click a button, and see something happen on the screen in response to the click. We have a lot to learn in the meantime, but weâll take it step by step.
jQuery has some built-in
functions that allow us to access elements from the DOM. Hereâs an example of accessing an h1
element.
<h1>Hello, World!</h1>
var header = $('h1');
console.log(header);
//=> "k.fn.init(0)"
Letâs break this down:
$
- This dollar sign is packed with functionality! It gives the instructions: go to the HTML document, and find a specific element.('h1')
- this is the argument passed to the$
function. It says: go look in the HTML document for all theh1
elements that you find.- Since we stored the value of this in the
header
variable, we canconsole.log()
this and see the HTML element.
The output of k.fn.init(0)
may look strange and not helpful. If you click the small arrow to the left of it, you should see something like this:
This still may feel strange, but letâs dig into it. Notice that one the second line, we now see 0: h1
. This is saying that the first (and only) element that was found and stored to this variable was an h1
element.
If you hover over that line that says 0: h1
, you will see the element in the browser become highlighted.
To make this feel a little more helpful, we can ask for the text inside of the h1
element, with this syntax:
<h1>Hello, World!</h1>
var header = $('h1');
console.log(header.text());
//=> Hello, World!
Accessing Elements with Class Names
We can also access elements by classes. Instead of ('h1')
we would need to write something like ('.class-name')
, using the same selectors we would when writing CSS rules for classes.
Try It: Accessing Elements
Use this Glitch project as a starter. We will use this project throughout today's lesson.
First, familiarize yourself with the existing HTML elements. For this activity, you should not need to change the HTML.
In your JavaScript file, write code to access each element and store in a variable, then print to the console. Practice accessing elements by element type or class. In the console, you should see your console.log
statements.
Click here for a Medium Challenge đ¶đ¶
Create a duplicate of the h1
element in the HTML and check the console. Was anything different printed this time? Why? What does this tell you about the importance of using classes?
Change Content on the DOM
Now that we can access elements and store them in a variable, the possibilities are endless! Letâs start by programmatically changing the content of an element. We can use .text()
to change the text inside of an element.
<h1>hello</h1>
var header = $('h1');
header.text("HIIII");
//=> In the browser, the hi now says HIIII
Whatâs happening? The h1
element has a method called text
. When we originally wrote the h1
, we gave it a text
value of âhelloâ by typing âhelloâ between the tags. jQuery provides us with a method to change that original text. Whatever string is passed into, or typed into the parenthesis after .text
, will replace the text inside of the h1
.
Try It: Change Text
Continue working in the Glitch project from the last Try It.
By only adding code to the JavaScript file, change the text inside of at least two elements.
Click here for a Medium Challenge đ¶đ¶
If you changed the text of the h1
on one line of code, then on the line below changed it to something else, which one would show in the browser? Why?
This was interesting, but we could have just written different text inside the HTML tags to accomplish what we just did here. As was mentioned earlier, we are taking todayâs concept step by step. Move on to the next section and youâll start seeing some âšmagicâš happen!
Events
Events are really at the core of DOM Manipulation. When we talked about user interaction earlier, thatâs exactly what we mean. An event is any action that the user takes while on our site. Clicking a button, scrolling down, hovering over something, and more.
Event Listener
Imagine that youâve just ordered food for delivery and are waiting for it to arrive. When the doorbell rings, youâll stand up from the couch, walk over to the door, open it, and take your food. Guess what? You programmed yourself with an event listener.
In order for our site to respond to events, we need to write some code so that our site becomes âsmartâ enough to look out for a specific event on a specific element. This âlook outâ is called an event listener. Their job is to sit around and wait for an event to take place in the browser, and call a function for us when it does.
The Glitch project below has an example of the syntax. Click View Source to look at the JavaScript. Back in View App: Click the button. Click the button a second time. What happens each time you click the button?
đŁ Discuss
With your breakout group, read through each line of the JavaScript file in the Glitch project above. Lines 4 and 9 should be somewhat familiar; but line 6 is brand-new. What is your prediction about what each part of the code is doing?
Click here for a Medium Challenge đ¶đ¶
The function doSomething
is never called with the syntax we've learned: doSomething()
. Why not? What happens if we add ()
after doSomething
on line 3? Remix the project to find out!
Takeaways:
Line 4
declares a variable that stores thebutton
elementLine 6
creates an event listener. Our program will now be âon the lookoutâ for a click that takes place on the button. It wonât listen for clicks anywhere else. It wonât listen to any other events on that button. Just a click and only on that button. When that button is clicked, it will call the functiondoSomething
.Line 8
declares the functiondoSomething
. Itâs just a set of directions, waiting around to do its job. It will be called when the button is clicked.
Event Handlers
The event listener is responsible for monitoring an element for an event and doing something when the event occurs. The event handler is the function thatâs called when the event occurs. In our previous example, the function doSomething
was our event handler. These terms are commonly used interchangeably.
Try It: Event Listeners & Handlers
Go back to the Glitch project about Baby Seals.
Add a button
element in the HTML.
Now, update the JavaScript so that when the button is clicked, the text in the h1
changes to something that it wasn't originally.
When you're done, answer these questions with your partner:
- What line of code is your event listener on?
- What type of event is your listener on the lookout for?
- What is the name of your event handler?
Access CSS
One cool thing about JavaScript is that since itâs accessing your HTML elements, you can also access the styles that have been applied to each element. It works kind of like text()
; thereâs a property on the element that we can change. We can add, remove, replace, or toggle CSS classes!
Check this out:
đŁ Discuss
Remix the Glitch project above, then answer these questions with your breakout group:
- Why does the button go back and forth between pink and purple?
- Try changing
.toggleClass
to.addClass
- what happens? - What happens when you change
.toggleClass
to.removeClass
? Why? - Uncomment line 11 in the JavaScript file then click the button a few times. What happens? Why?
Takeaways:
.addClass
will add a class to an HTML element.removeClass
will remove a class from an HTML element.toggleClass
will check if an HTML has a specific class. If it does, it will remove the class. If it doesnât, it will add that class.
Besides accessing CSS rules by classes, we can also add CSS property/values! Check out the code in the project below:
Letâs break this down.
- On lines 4-5, we declare the
changeBackgroundBtn
andcontainer
variables which are storing the button anddiv
, respectively - On line 7, we declare an event listener for the
changeBackgroundBtn
button - On line 9, we declare the
changeBackgroundColor
event handler - Line 10 is where the magic happens:
container.css('backgroundColor', 'mediumaquamarine');
container
references thecontainer
variable.css
says: Iâm about to give you directions on adding styles, or CSS rules..css
takes two arguments, a property, and a value.'backgroundColor'
says: here is the property Iâd like you to add to this element'mediumaquamarine'
says: here is the value Iâd like you to update this property to. We can give any valid color name, hex code, or rgba value. It must be in a string.
This entire line of code accesses the div
element and updates that elements styles, so we see the background color change in the browser!
Practice: DOM Manipulation
Ever wonder how sites or apps create the "dark mode" feature? You're about to do just that!
You can either work off of the Baby Seals Glitch project, or start with this one!
Create two button
elements in your HTML, both nested inside of a div
. One button should be labeled "light mode" and the other "dark mode". They will both need their own class name.
Now, write the JavaScript so that when the dark mode button is clicked, the background color of the div
changes to a dark color. When the light mode button is clicked, the background color should change to a light color.
Click here for a Medium Challenge đ¶đ¶
When an application uses dark mode, not only the background color changes; so do fonts, colors, etc. Add a few more elements to your HTML. When each button is clicked, those elements should change colors appropriately.
Click here for a Spicy Challenge đ¶đ¶đ¶
In addition to light and dark mode, add a "party mode" button. When clicked, the user should see a screen that looks like a party! Use a background image
instead of a background color. Have some fun with it!