Document Object Model
Last updated
Was this helpful?
Last updated
Was this helpful?
The Document Object Model (DOM) bridges the gap between HTML elements and JavaScript. It allows us to, among other things, dynamically change a website. The DOM is structured like a tree, with the global `document` variable functioning as its root.
Selecting elements that exist in the DOM is a common use case. You can think of selecting as finding one or more elements that match some query.
Imagine that we have to find a list of groceries in a website.
Conveniently the website has a `li` element for each grocery. To extract the groceries (in this case Milk
, Bread
and Cheese
) we would need to query the DOM to find the element in question.
The groceries
variable now references all the li
elements. To access the text within the elements, as we originally set out to do, we can simply retrieve the innerText
property.
There are many more ways of selecting elements. To mention a few useful ones:
document.querySelector
, document.getElementById
and document.getElementsByClassName
.
Changing an element in the DOM is also a common use case.
Building on our previous example, imagine that we wanted to change the Milk
grocery to Juice
.
First we would have to select the element using what we learned from the previous section. And then we change the text by simply assigning a new string to the innerText
property.
Up until now we have only looked at selecting and changing elements that already exist. But adding new elements can also be very useful.
Let's add another grocery to the list: Soap
.
When adding new elements to the DOM we add child elements to parent elements. In order to add another grocery to the list we first need to find the parent element. In our example the parent element of the groceries is the ul
(unordered list) element.
Next we need to construct the li
element for Soap
and append it as a child to the groceryList
.
Finally we may want to remove elements from the DOM.
Let's remove Milk
from the list of groceries. To do so we need to select the element we want to remove and its parent element.
Conveniently we can retrieve the li
element for Milk
by referencing the firstChild
property of the ul
element. We then proceed to call removeChild
providing the item we want to purge from the list.