Skip to main content
- React Components and Component State
- Composing React Components and Passing Data Via Props
- Component Side Effects
- Advanced Styling Techniques
- React Components and Component State
- Composing React Components and Passing Data Via Props
- Component Side Effects
- Advanced Styling Techniques
Now that we can build a basic static web page with HTML and CSS, we need to add functionality to the page. The first step in building vibrant dynamic web pages and applications is learning about the DOM. What it is, how it affects our page, and how to access and manipulate it. DOM manipulation is at the core of every framework and before we start using frameworks we need to understand the DOM.
At the end of this module, you should be able to:
- explain what the DOM is, and how it relates to an html page
- use DOM selectors, and describe the differences in the behavior of each
- use different properties and methods to manipulate a selected element
- create a new element, manipulate it, and add it to the DOM
When talking about your journey, don’t focus on things you don’t know yet, focus on what you’ve learned and how quickly.
Review each preclass resource before class.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
The Document Object Model is an object representation of the html elements of a webpage. It gives us an interface that with which we can interact with and manipulate the page, changing document structure, content, and styling. The object model is a tree structure with each DOM element therefore being a tree node, containing all the same property keys as each other node. Some of these node properties are informational while others are methods that we can use for interaction. The DOM , creating and propagating event objects, which hold information about the event type and target, up the tree.
When a web page is loaded into a browser, the browser first looks for the HTML file. The browser uses the HTML file as a blueprint, or instructions on how to build the page (this coupled with the CSS file later). The browser parses these instructions and builds a model for how the page should look and act using Javascript. This model is a Javascript Object containing every element in order on the page. This Object is referred to as the DOM, or Document Object Model.
The DOM is built as a data structure known as a ‘Tree’, because parent elements have nested children elements (or leaves). As with physical trees, we can follow branches of the tree to get to the exact leaf (or leaves) that we want to access. Each branch of our DOM tree can be it’s own tree. It is important to remember this as we move through this lesson.
When the DOM is built and the webpage is loaded, developers get access to it in the form of the global Javascript object document. document contains the entire hierarchy of the page, each element (or DOM node), and it also contains dozens of built in methods and properties. We can use these methods and properties to manipulate what we see on the screen.
- Note: There are so many methods and properties on document (and its subsequent elements and collections) that it would take a lot longer to properly cover them all. We will only be covering the few most commonly used. From this point forward you will be expected to reference the official documentation to learn more about the different methods and properties available, when your need arises for something other than what we have taught. This is a very good habit to get into as we progress deeper in to the course.
Lets investigate the DOM together by visiting a live website and updating the DOM. Follow these steps in order:
Prerequisite: This tutorial assumes you are using Google Chrome. You can get similar results in any other browser but these steps were tailored for a chrome experience.
- Navigate to lambdaschool.com.
- Right click on the main heading and you should see a dropdown with an option to
inspect element.Click that option and chrome developer tools should activate. - The developer tools should be showing the selection you made when you right clicked. Double click the content of the heading. You should now be able to edit the text of the header.
- Update the text with anything you’d like. For this example, I will update the text to say “Hello there!” You won’t see any changes until you deselect the content in the chrome developer tools.
- Now try updating the content and HTML of other elements on the page.
Notice that if you refresh the page, the changes you made are gone! That is because the elements you were editing existed in the DOM and were not permanent!
You now have experience editing the DOM without writing code. Go check out the challenge below to see the DOM inside the console!
Open the console in your web browser and enter
console.log(document);
This should make the document appear on the screen, play around with it for a minute. Notice how the document contains all of the HTML elements (otherwise now known as DOM nodes) on the page. Hover over these nodes and notice how the element on the page is highlighted.
- Live DOM Viewer
This live DOM viewer exposes the DOM in a great way for learning - Eloquent Javascript: DOM
A fantastic chapter on the DOM from the book, 'Eloquent Javascript' - MDN 'document' documentation
Official documentation for the 'document' Javascript object - MDN DOM documentation
Official DOM docs
Being able to select specific parts of the DOM is key to building user interface experiences. Learning about the several ways we can do this using DOM and nuances between each will lay the foundation for some amazing interactions.
Now that we know how to access the DOM using Javascript, we need a way to select individual elements (or groups of them). Doing so will give us access to all live elements and allow us to manipulate them.
To manipulate elements on the DOM, we need to select them. There are many ways of doing this; for example, we can select the body and the head just by asking for them (document.body, document.head). But, when we want to go deeper, that’s where things get complicated. Thankfully, document has several built-in methods for accessing the exact element(s) we want.
It is important to note that all of these methods are case sensitive. If you are unsure of the case while using them, please refer to the official documentation.
These are the original methods for selecting elements from the DOM. They each take a single string as the only argument, containing either the id or class you are looking for.
document.getElementsByTagName(‘p’);
This method will take a single string as an argument containing the element name of the elements you want to select. It will return an array-like object called an HTMLCollection containing all the elements that contain the element name supplied. We will discuss what aHTMLCollection is after we talk about the rest of our selector methods.
document.getElementById(‘idName’);
This method will take a single string as an argument containing the id of an element, search through the DOM, and return the matching element.
document.getElementsByClassName(‘className’);
This method will take a single string as an argument containing the class of the elements you want to select. It will return an array-like object called an HTMLCollection containing all of the elements that hold the given class.
These are the newest element selection methods added to the DOM. These methods allow us to select element(s) based on CSS style selectors (remember . is class and # is id). Each method takes a string containing the selectors and returns the element(s). Note - we can select by element, id, class, or others with both methods.
document.querySelector(‘.custom-style’);
This method will search for and return the first element that matches the value passed into the method. Remember from above that the biggest change from the older DOM selection methods is that we now need to pass the proper CSS selector into the argument.
If we passed (‘custom-style’) and not (‘.custom-style’) we would error out.
document.querySelectorAll(‘queryString’);
This method will search for and return ALL elements matching the query string. This method returns these elements in an array-like object called a NodeList
When we use getElementsByClassName() or querySelectorAll() we get back either an HTMLCollection or a NodeList respectively. We refer these to as ‘array-like objects.’ We have seen an array-like object before (the arguments object in a function). They both have numerical zero-based indices and the length property, but that is all they share with an Array. NodeList does take it one step further, and has access to .forEach. There are no .reduce or .map or any other array method.
Pro tip: The Array class contains a method we can use to create an array from an array-like object, called .from(). To use this, we would give .from the array-like object as its only argument.
Array.from(arrayLikeObject)
Let’s get some practice using different selector methods. You can use this code or write your own.
Study this HTML first:
<header>
<h1 class="main-header">Selectors!</h1>
<nav class="main-nav">
<a href="#" class="nav-item">Home</a>
<a href="#" class="nav-item">About</a>
<a href="#" class="nav-item">Blog</a>
<a href="#" class="nav-item">Contact</a>
</nav>
</header>
What if we wanted to select all the first a tags within our navigation? There are several ways to accomplish this task, but let’s use querySelector() to get started.
When working with the DOM, we may want to re-use the reference several times in our code. Let’s declare a const to hold our DOM reference:
const mySelection = document.querySelector(‘a’);
Notice we had to use document in front of querySelector() that is because querySelector is a method of the document object.
Next, let’s log the result of our selection.
const mySelection = document.querySelector(‘a’);
console.log(mySelection);
We should see this log in the console:
“<a href=’#’ class=’nav-item’>Home</a>“
We now have access to that element node in the DOM! What if we wanted to select multiple elements at once? We have just the method for that: querySelectorAll().
If you recall from the introduction to selectors, querySelectorAll() will allow us to return an array-like object called a NodeList. Let’s set up a new const for our new selection:
const multipleSelections = document.querySelectorAll(‘a’);
Notice that all we changed on the right side of the operator was adding an “All” to “querySelector.” The returned value is very different though, check your console’s log to see what happened. If you are using chrome developer tools, you will see something like this in your console:
NodeList(4)
0: a.nav-item
1: a.nav-item
2: a.nav-item
3: a.nav-item
length: 4
__proto__: NodeList
Wow, that is totally different than our result from querySelector() in the first example! We now have a NodeList and all of the nodes matching the a elements.
What can we do with a NodeList? You can dig deeper into the documentation, but for our tutorial, let’s see how it is “array-like.”
Study this code:
const multipleSelections = document.querySelectorAll(‘a’);
console.log(multipleSelections[2]);
Notice the multipleSelections[2]. That looks very similar to how we can use indices in arrays. The log result from the code above should read as follows:
“<a href=’#’ class=’nav-item’>Blog</a>“
Being able to access elements in this way is extremely powerful and will allow you to be creative if an HTML solution is not possible. Imagine you didn’t have a class or ID to hook into, you could use the NodeList index to get the job done!
When using querySelectorAll() don’t forget it requires you to use the proper CSS selector. Using the same HTML example:
<header>
<h1 class=”main-header">Selectors!</h1>
<nav class="main-nav">
<a href="#" class="nav-item">Home</a>
<a href="#" class="nav-item">About</a>
<a href="#" class="nav-item">Blog</a>
<a href="#" class="nav-item">Contact</a>
</nav>
</header>
Use querySelectorAll() to select all the nav-item classes:
const multipleClasses = document.querySelectorAll(‘.nav-item’);
Note that we had to type out the . in .nav-item. This trips up new developers to JavaScript all the time. If you were to log out the results of this session, you would see it’s just a NodeList like before, but now it’s using classes instead of the a element. Push yourself further by using the challenge below!
Finish the DOM selector requests based on given HTML, LESS, and JS - follow this link for the challenge.
Being able to change live DOM elements is part of any front end web developers tool kit. Updating text, HTML attributes, or styles is part of building interactive web sites and web apps.
Now that we have access to element(s), we can start to manipulate them and change their characteristics from the original html.
After we have captured our element (eg. const el = document.querySelector(‘#idName’); we can use that instance of the element we selected to access and assign values to properties natively contained on it. Once again, there are dozens of properties and methods given to us on each element. Here are a few of the most commonly used properties:
- Gets and sets the text of an element. Essentially whatever text is between the open and closing tags of an HTML element.
- Can use the assignment operator ( = ) to reset the text of an element
- Setting this property on a node removes all of its children and replaces them with the new single text node.
<div>Something Here</div>element.textContent = 'Something New;
- This method (or property) is used as a way to set or reassign an attribute on the element.
- ‘.setAttribute()’ is a method that takes two arguments, the attribute to set, and the value to set to that attribute.
- eg:
element.setAttribute('src', 'http://www.imagsource.com/image.jpg') - Can also use the pattern:
element.'attrName' = ‘value’. - eg:
element.src = 'http://www.imagsource.com/image.jpg'
- Every element contains a style object. This property accesses that style object. The style object contains every available style as a key and a value as the value. It is important to note, that these are NOT the CSS styles, these are inline HTML styles.
- These styles are associated with the HTML inline style set on the element
- eg:
<div style=“color: red;”>DIV STUFF</div>
- eg:
- You can access and change a property on the style object by using the assignment operator
=. - eg:
element.style.color = ‘blue’; - Changing a property on the style object will effectively give this element an inline style.
- Inline styles have the highest specificity, overriding any other selector except
!important. - VERY IMPORTANT to note that this does NOT access or change anything in the CSS file.
.classNameaccesses or assigns a string containing all of the classes on the element..idaccesses or assigns a string containing the id of the element.
classListwill return an array-like object of all the classes on the element. There are many useful methods available onclassList.classListis aDOMTokenList.- A
DOMTokenListis an array-like object with a numerical zero-based index, a length property, also the.contains()and.forEach()methods.
- A
- Most notably the methods
.add().remove()and.toggle()exist. All three take a single string representing the class..add('className')and.remove('className')do as their names indicate..toggle('className')will add the class if it does not exist and remove it if if does.
- These methods add child elements to parent elements.
.appendChild(child)will take an element and add it to it’s children. It will add it to the ‘end’ physically so if the children are displayed in order it will be the last.- eg:
parentElement.appendChild(childElement)
- eg:
.prepend(child)adds a child to the beginning, displaying it first.- eq:
parentElement.prepend(childElement)
- eq:
- These properties are used for accessing relatives of the element.
.childrenreturns anHTMLCollectionof all the children of that element..parentNodereturns the parent element of that element.
Let’s get some practice manipulating the DOM. You can use this code as a base for your JavaScript or write your own HTML and CSS along the way.
When we want to update the text using the DOM, the go-to property is called textContent. We can both read and write text inside of elements using textContent.
Given this HTML, lets make some updates to the text:
<h2 class="second-heading">I am the DOM</h2>
First, lets set up a reference to our element on the DOM:
const secondHeading = document.querySelector('.second-heading');
We are now prepared to update the content of our heading. Let’s update the content to say “DOM updated!”
secondHeading.textContent = "DOM updated!";
Notice that we are first getting the text node of the element and then setting a new value!
Security Note You may read about innerHTML in your DOM learning. Avoid using innerHTML as it could potentially be used as an attack vector for cross site attacks.
Updating HTML attributes is vital to DOM manipulation. Let’s update the style for the h1 in the code below.
<header>
<h1 class="main-header">Dom Manipulation</h1>
<nav class="main-nav">
<a href="#" class="nav-item">Home</a>
<a href="#" class="nav-item">About</a>
<a href="#" class="nav-item">Blog</a>
<a href="#" class="nav-item">Contact</a>
</nav>
</header>
Updating the DOM usually happens in two steps:
const mainHeader = document.querySelector('.main-header');
mainHeader.style.color = 'red';
You can even chain the two steps together like this:
const mainHeader = document.querySelector('.main-header').style.color = 'red';
This two-step process can be repeated for other attributes as well! What if we had an empty src attribute on an image tag? Let’s try it out provided we have this HTML:
<img class="custom-img" src="" alt="Kitty image" />
Select the image element’s class and update the src attribute with this link:
https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350
const customImg = document.querySelector('.custom-img');
customImg.src = 'https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350';
When using JavaScript to update CSS style properties, we need to be careful to remember that JavaScript does not accept dashes as a valid naming value! Whenever a CSS property contains a dash, we must use camel casing in JavaScript.
Example:
.some-class {
background-color: gray;
}
The JavaScript version would look like this:
const someClass = document.querySelector('.some-class');
someClass.style.backgroundColor = "gray";
Pro Tip: Don’t forget the string when you assign a value to a CSS property.
Take the example code from your tutorial and try updating the DOM in various ways.
Here are some ideas:
- Change the color of the paragraphs
- Change the text contents of any element of your choosing
- Change the
hrefof an anchor tag - Update the
alttag of an image - Update layout styles, try out flex properties with JavaScript syntax
A student should know how to dynamically create a new element and add it to the DOM.
An important feature of the DOM is the ability to create brand new elements dynamically. Using the document.createElement() method, we will be able to create a brand new element, style it, and add it anywhere on the DOM we would like.
.createElementcreates a brand new element based on a given string.- New element exists in memory, but not on the DOM yet.
- Can use any DOM property or method to style and manipulate the element.
- eg:
document.createElement('h1')will create anh1element.
- Add child elements to parent elements.
.appendChild(child)add an element to it’s children. Adds to the ‘end’, so that if displayed in order, the added child will be last.- eg:
parentElement.appendChild(childElement)
- eg:
.prepend(child)adds a child to the beginning, displaying it first.- eq:
parentElement.prepend(childElement)
- eq:
Practice the concepts covered.
-
Manipulating the DOM with JavaScript, using selectors.
You can use class recordings to help you master the material.
-
DOM I for WebPT22 w/Keiran Kozlowski
Now that we can build a basic static web page with HTML and CSS, we need to add functionality to the page. The first step in building vibrant dynamic web pages and applications is learning about the DOM. What it is, how it affects our page, and how to access and manipulate it. DOM manipulation is at the core of every framework and before we start using frameworks we need to understand the DOM.
To demonstrate mastery of this module, you need to complete and pass a code review on each of the following:
-
Objective challenge:
Open the console in your web browser and enter
console.log(document);This should make the document appear on the screen, play around with it for a minute. Notice how the document contains all of the HTML elements (otherwise now known as DOM nodes) on the page. Hover over these nodes and notice how the element on the page is highlighted.
-
Objective challenge:
Finish the DOM selector requests based on given HTML, LESS, and JS - follow this link for the challenge.
-
Objective challenge:
Take the example code from your tutorial and try updating the DOM in various ways.
Here are some ideas:
- Change the color of the paragraphs
- Change the text contents of any element of your choosing
- Change the
hrefof an anchor tag - Update the
alttag of an image - Update layout styles, try out flex properties with JavaScript syntax
-
Objective challenge:
Practice the concepts covered.
-
Project: DOM I
