Do you remember how a HTML webpage is created? You use html tags, to create the structure of the page, and style it with CSS.
Here you can see an example of a simple webpage:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundations of Programming</title>
</head>
<body>
<h1>Foundations of Programming</h1>
<p class="text">
Welcome to the course. You can find all infos on the
<a href="https://pixelkind.github.io/foundationsofprogramming/">course website</a>.
</p>
</body>
</html>
What is the Document Object Model
A HTML document has a nested structure that you can also visualize as a tree structure like this here:
The structure of the HTML document
You can see the same elements that are in the code, represented in the diagram.
To access elements of a HTML document in JavaScript, we need a programming interface and that is called Document Object Model, or short DOM.
The DOM defines:
- the HTML elements as objects
- the properties of these HTML elements
- the methods to access the HTML elements
- the events for all HTML elements
With the DOM, we can interact with the page and manipulate it. We can change, add or remove elements, change CSS styles, and we can react on events. We will talk about events in the next chapter.
Why is it useful?
Simple examples could be, that you want to execute a JavaScript function when the user clicks a button. Or you want to change the content or color of a HTML element when a user clicks a button. Or you want to dynamically load data and update your page correspondingly, for example with weather information.
How to connect HTML and JavaScript
You can write JavaScript directly inside the HTML document, in a script tag. But this is not recommended.
1
2
3
<script>
console.log("Hello World!");
</script>
Instead you reference an external JavaScript file and load it like this:
1
<script src="path/example.js"></script>
Please note, you need to open and close the script tag. It is not enough to use a self-closing tag.
Where should I place the script tag
The default place is the head
of your HTML document, but you can put the tag also in your body, for example as last element. A script tag will never be visibly rendered in the browser.
You remember that the order is important when programming. If you place the script tag in the head of your HTML document, it might be loaded and executed before the rest of the page has finished loading. In this case you cannot access the DOM.
You will learn in the coming chapter (Events) how to handle that. If you place the tag at the end of your body, it will be loaded and executed after your document has loaded.
Accessing element in HTML through JavaScript
You can access elements in the DOM in different ways, either by their id or name, a css-class or their tag-name. You get back the reference to the corresponding objects on your HTML document.
Get an element by a CSS selector
On the document
object you can call the function querySelector
and provide the CSS-selector that you want to get back the first HTML element that matches in your document. This method works with all selectors: class, tag and id. You use the same selector as you would use in your CSS file.
1
2
3
<div class="results">
<p id="score">42</p>
</div>
1
const resultElement = document.querySelector(".results");
In this example, we want to get the first of all elements that have the results
class applied.
Please note that this method will always return the first element that matches the query.
Get an element explicitly by its ID
If you want to access an element by its unique id, you can use the method getElementById
on the document
object. If an element exists with this id in the DOM, it will be returned.
1
2
3
<div class="results">
<p id="score">42</p>
</div>
1
const scoreElement = document.getElementById("score");
Please note, this will always return the object directly, not an array.
Get elements by class
If you want to get a list of all elements that have a specific class applied to them, you can use the method getElementsByClass
on the document
object.
1
2
3
<div class="results">
<p id="score">42</p>
</div>
1
const resultElements = document.getElementsByClass("results");
Notice the plural of the function name and the variable name. This method will always return an array.
Get elements by tag name
If you want a list of all elements of a specific tag, you can use the method getElementsByTagName
on the document
object.
1
2
3
<div class="results">
<p id="score">42</p>
</div>
1
const paragraphs = document.getElementsByTagName("p");
HTMLElement
When you access a single element through one of the methods above, you will get back a HTMLElement
. This element has different properties that you can use to manipulate it.
Here you find more information about HTMLElements.
Changing elements
If you want to change the content of an element, you first need to get a reference to it using one of the mentioned methods above.
Next you have to decide what you want to change, the innerText
or the innerHTML
. With innerText
you can only change the text that is displayed in this node. With innerHTML
you can set HTML code instead of pure text.
Let’s have a look at an example:
1
2
3
<div class="results">
<p id="score">42</p>
</div>
1
2
const scoreElement = document.getElementById("score");
scoreElement.innerText = "301";
The resulting HTML would be:
1
2
3
<div class="results">
<p id="score">301</p>
</div>
If you would use innerHTML
, you could also write a HTML string in JavaScript, for example add another tag to it.
Adding elements
If you want to add elements to an existing HTML document, you can create new tags and add them with the command appendChild
.
Here you can see an example of it:
1
2
3
4
5
const card = document.createElement("div");
const content = document.createTextNode("🐹");
card.appendChild(content);
const container = document.getElementById("container");
container.appendChild(card);
Another way of writing could be:
1
2
3
4
const card = document.createElement("div");
card.innerText = "🐹";
const container = document.getElementById("container");
container.appendChild(card);
Here is the resulting HTML:
1
2
3
<div id="container">
<div>🐹</div>
</div>
We just created a div with a Hamster emoji as text inside.
Notice that createTextNode
and innerText
leading to the same result.
Removing Elements
If you want to remove an element from a HTML document, you first have to get a reference to it, and then remove it from the parent element with the command removeChild
. You can access the parent element with the parentNode
property of an HTMLElement.
1
2
const element = document.getElementById("name");
element.parentNode.removeChild(element);
Adding or removing styles
If you want yo add or remove a style to a HTML element dynamically you first have to get a reference to the corresponding element. Now you have different opportunities.
You can either use the style
property of the HTML element to add a so called inline style applied directly to the element.
1
2
const element = document.getElementById("title");
element.style = "color: #ff00ff;";
This would be the result:
1
<h1 id="title" style="color: #ff00ff;">Hello NMD</h1>
Or you can add or remove a CSS class with the classList
property and the methods add
and remove
. You can also use the method replace
to replace an existing class on an element with another one.
Here is an example of adding a class to a HTML element:
1
2
const element = document.getElementById("title");
element.classList.add("headline");
This would result in this HTML code:
1
<h1 id="title" class="headline">Hello NMD</h1>