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 CodePen quite a bit up until now; the Chrome Dev Tools are a bigger 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.
Turn & Talk
Visit your favorite site. Write a list of at least 3 places you think the developers used DOM manipulation.
opportunity for sponsor integration
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.
JavaScript has some built-in
functions that allow us to access elements from the DOM. Here’s an example of accessing an h1
element.
var header = document.querySelector('h1');
console.log(header);
//=> "<h1>hello</h1>"
Let’s break this down:
document
- this tells the computer: please go over to the HTML document.querySelector
- now that the computer is looking at the HTML document, this instruction says: I’d like you to look for something specific('h1')
- this is the argument passed to the.querySelector
function. It says: go look in the HTML document for the firsth1
that you find.- Since we stored the value of this in the
header
variable, we canconsole.log()
this and see the HTML element.
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
Create a new CodePen.
In your HTML file, write at least 3 HTML elements. Give at least one of the elements a class.
In your JavaScript pane, write code to print each element to the console. Practice accessing elements by element type or class. In the console panel, you should see your console.log
statements.
Medium Challenge: Create a duplicate of one of your elements in HTML and run the code again. Was anything different printed in the console? Use your google skills to research the difference between .querySelector
and .querySelectorAll
.
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! Here’s one example:
var header = document.querySelector('h1'); // JavaScript
var header = $('h1'); // jQuery
In jQuery, we can use the $
in place of the document.querySelector
which saves us time typing!
Pro Tip
When you access an element with jQuery, it's a little larger than when you do it with vanilla JavaScript. For this reason, when you console.log
a variable that stores an element, the CodePen console will not be able to print it out.
This is where your Chrome Dev Tools skills that you learned in the Warm Up will come in! Remember, you can console.log
more than one thing at a time, so something like console.log("This is my button:", button);
may be helpful in order to keep track of what is what in the console.
Load jQuery into a CodePen
jQuery doesn’t just magically “work” in a JavaScript file; we have to import the library. To do this, click the gear icon to open the settings next to “JS.” Under “Add External Scripts/Pens,” start typing in “jQuery,” then select the first option. Click “Save & Close.”
Keep in mind that when we use features of jQuery, we are still writing JavaScript. It’s just a little “extra” on top! From here on out, we will use the jQuery $
to access DOM elements.
Try It: Access Elements with jQuery
Create a new CodePen. Follow the steps above to load jQuery into this pen.
In the HTML file, create an h1
and two p
elements.
In the JavaScript file, use the jQuery $
syntax to access all three elements and store them in variables. Then, console.log()
all three variables to make sure you stored the elements correctly.
Keep in mind that from here on out you'll have to do this for each CodePen that you are going to use the jQuery $
in!
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 a tool called .text
to change the text inside of an element.
var header = $('h1');
header.text("HIIII");
//=> In the browser, the hi now says HIIII
What’s happening? The h1
element has an attribute 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 CodePen from the last Try It.
By only adding code to the JavaScript file, change the text inside of all three elements.
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 Event Listeners,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
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.
This CodePen has an example of the syntax. Click “Edit on CodePen” to open it in the browser. Click the button. Click the button a second time. What happens each time you click the button?
See the Pen Check It Out: Event Listeners by Turing KWK (@turing-kwk) on CodePen.
Turn & Talk
With your partner, read through each line of the JavaScript file in the CodePen above. Lines 1 and 5 should be somewhat familiar; but line 3 is brand-new. What is your prediction about what each part of the code is doing?
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?
Takeaways:
Line 1
declares a variable that stores thebutton
elementLine 3
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 5
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
Create a new CodePen and load jQuery into it.
Create an h1
and button
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:
See the Pen Check It Out: ClassList Property by Turing KWK (@turing-kwk) on CodePen.
Turn & Talk
Fork the CodePen above, then answer these questions with your partner:
- 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?
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 pen below:
See the Pen Check It Out: DOM Manipulation of CSS by Turing KWK (@turing-kwk) on CodePen.
Let’s break this down.
- On lines 1-2, we declare the
changeBackgroundBtn
andcontainer
variables which are storing the button anddiv
, respectively - On line 4, we declare an event listener for the
changeBackgroundBtn
button - On line 6, we declare the
changeBackgroundColor
event handler - Line 7 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 a "dark mode"? You're about to do just that!
Create a new CodePen and load jQuery into it.
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.
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.
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!