What is the DOM? DOM stands for Document Object Model and key is in that second word ‘object’. The document is an object like any other objects in JavaScript. It’s an object for the whole page.
If you go to the console of your browser’s dev tools you can see it. Type document
and press enter. In Chrome you see something that looks just like the HTML of the page. To see the same in Firefox click on the Inspector tab.
However try typing this into the consul.
document.body.style.backgroundColor = 'blue';
The page will change colour but if you look at the DOM you’ll see that the body tag now has a style tag with background-color: blue
.
So now it’s not the same as the HTML of the page. The DOM is the HTML of the page plus any changes made to it by JavaScript. The browser may also implement some changes to it too, for instance to correct errors like adding <tbody>
tags to a <table>
if they’ve been omitted.
Nodes
The DOM tree is made up of nodes. Every part of the DOM is a node and there are several types of node. The main ones are:
- element nodes (type 1) are simple HTML elements like
<body>
tags etc. - attribute nodes (type 2) are the attributes of HTML elements.
- text nodes (type 3) text that is not inside an element.
- comment nodes (type 8) are HTML comments.
In the elements tab of Chrome’s dev tools when you click on an element a code appears to the right like == $0
. This is a clue to the selected element.
Switch to the console and type $0.nodeType
. It will return a number corresponding to the type above. You can also use $0.nodeName
which gives you the name. Click on the <header>
element and $0.nodeName
is HEADER
.
You can also access them like so: document.body.nodeType
.
Accessing the DOM
The main ways to access the DOM with JavaScript are:
Method | Code | Notes |
---|---|---|
by ID name | document.getElementById('id-name'); |
|
by class name | document.getElementsByClassName('someclass'); |
This creates an HTML collection that can be accessed like an array with an index. myClassNames[2] |
by tag type | document.getElementsByTagName('p'); |
|
by selector | document.querySelector('#name'); |
|
by selector | document.querySelectorAll('class-name'); |
retuns a node list (works like an array) |
NB. Some of these are plural: elements
not element
. These 3:
getElementsByClassName
getElementsByTagName
querySelectorAll
will select All of the elements of the said type and store them in an array. You must either access them individually using array notation or all of them with a forEach
loop.
To access individually:
const someClass = document.getElementsByClassName('some-class');
someclass[2].style.border = 'solid white 3px`;
This is great because you can set up one variable to select all of them rather than one for every one as you would using getElementById
.
However if you want to target all of them it’s necessary to use a for
loop. However a more modern way is to use the querySelectorAll
method instead. A loop is still required though it’s easier with a forEach
loop as it’s simpler to write.
Query selectors
There are two query selectors: querySelector()
and querySelectorAll()
.
The first works on single elements and if there are more than one it selects the first one.
const button = document.querySelector('#idName');
Once we have our element stored in a variable it can be accessed. Here we’re adding a click event to the button. It’s targeting itself (event target) and changing the background colour.
button.addEventListener('click', (e) => {
e.target.style.backgroundColor = 'purple';
});
Once you’ve selected something you can store it in a variable and manipulate the CSS via an inline style
attribute.
const sectionEl = document.querySelector('section');
sectionEl.style.border = 'solid 1px blue';
So to manipulate the DOM and therefore the whole page is fairly easy.
BUT REMEMBER
- To use camelCase for CSS where hyphens would be
- To use quotes around CSS properties
function goBlue() {
document.body.style.backgroundColor = 'blue';
}
How it works
- The word
document
refers to the fact that this is an object we are accessing. - The next word
body
, after the dot, is a property ofdocument
. - And
style
is a property of body. - So
backgroundColor
is simply another property which is the equivalent tobackground-color
in CSS. This will write the following into the DOM:<body class="The-DOM post page" style="background-color: rgb(17, 153, 221);">
document.getElementById(myIdSelector).innerHTML = 'My ID selector says...'
document.querySelector('h1').style.fontSize = '2em';
querySelectorAll()
This one works differently though.
document.querySelectorAll('p').innerHTML
The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
So the querySelectorAll()
method selects multiple elements or nodes at once. These are stored in an array which can be accessed via looping.
Here is a simple example using a forEach()
method. This selects all element with the class of class-name
and adds a purple border to them.
const myClass = document.querySelectorAll('.class-name');
myClass.forEach(item => {
item.style.border = 'solid 2px purple';
});
Below a selection of buttons are stored in an array named buttons
. Each time a button is clicked it’s background changes colour.
First of all a .forEach()
array method is used to loop over the node list. Each single item is given a name. Here I’ve simply used button
but it can be any name. This can then be referenced inside. An event listener is added to each button, listening for a click
event. The click then triggers a class to be added or removed to the element—the event target.
const blueBtns = document.querySelectorAll('.blue-btn');
blueBtns.forEach((btn) => {
btn.addEventListener('click', (e) => {
e.target.classList.toggle('blue-background');
})
});