Since the first lesson, the results of your code have only appeared in the console, and visitors never see the console. In this lesson JavaScript starts to change the page itself: it replaces a heading, changes a colour, adds a new paragraph.
It does that through the DOM (Document Object Model). When the browser reads your HTML, it builds a version of the page that JavaScript can change. That version is called the DOM. In the DOM, every HTML tag becomes an object that you can grab, change, add or remove. As soon as the DOM changes, what you see on the page changes too.
Grab an element, then change it
The page has one heading:
<h1>Old Title</h1>
This JavaScript changes that heading:
const title = document.querySelector("h1");
title.textContent = "New Title";
title.style.color = "blue";
documentis the whole page.document.querySelector("h1")looks for the first element that matches the selector"h1". Selectors are written as in CSS:"#container"for an id,".card"for a class. That element is stored intitle.title.textContent = "New Title";replaces the text inside that element.title.style.color = "blue";changes its text colour, the same ascolor: bluein CSS. The value is written as text, inside quote marks.
The result: the heading on the page now reads New Title, in blue.
If no element matches, querySelector returns null. The next line is then the same as writing null.textContent = ..., and you get the TypeError "Cannot set properties of null". When you see this error, check your selector again.
Property names must be exact
JavaScript treats uppercase and lowercase letters as different, so property names must be written exactly:
- CSS properties with a hyphen are written in camelCase in JavaScript: the hyphen goes away, and the next word starts with a capital letter.
background-colorbecomesstyle.backgroundColor,font-sizebecomesstyle.fontSize. textContentis written with a capital C. The browser doesn't recognisetextcontent, so the text doesn't change.- Event properties like
onclickare written all in lowercase (an event is something that happens on the page, such as a click). The function you store inonclickruns when the element is clicked:
const button = document.querySelector("#btn");
button.onclick = () => {
button.textContent = "Clicked";
};
When the button is clicked, its text changes. If you write onClick (with a capital C), the browser doesn't recognise it, so a click runs nothing.
Adding a new element
The page has one empty div:
<div id="box"></div>
This JavaScript makes a new paragraph, then puts it inside that div:
const p = document.createElement("p");
p.textContent = "Hello from JavaScript";
document.querySelector("#box").appendChild(p);
document.createElement("p")makes a new<p>element. You can't see it yet, because it has not been put on the page.p.textContent = ...fills in its text..appendChild(p)putspinside the element#box, as the last thing inside it. Only now does the paragraph appear on the page.
The result on the page: <div id="box"><p>Hello from JavaScript</p></div>. To remove an element, call p.remove().
textContent or innerHTML
These two properties treat HTML tags differently:
title.textContent = "<b>Hello</b>"; // shows exactly: <b>Hello</b>
title.innerHTML = "<b>Hello</b>"; // shows: Hello, in bold
textContent puts the text in as it is, so any HTML tags in it appear as plain text. innerHTML reads the text as HTML, so the tags in it really work. For plain text, especially text a user typed, use textContent. The reason: through innerHTML, harmful code hidden in the text can run too. This attack is called XSS.
⚠️ Why isn't the page changing?
- The script runs before the element exists. A
<script>in the<head>runs before the browser reads the<body>. At that moment the element doesn't exist yet, soquerySelectorreturnsnull. Put the<script>at the end of the<body>, or use<script src="app.js" defer>, which delays the script until the whole page has been read.deferworks only on a script loaded from a file (one withsrc). On a script written directly between the<script>tags, the browser ignoresdefer. querySelectoronly grabs one.querySelectorstops at the first element that matches. To grab all of them, usequerySelectorAll.- An element made but never added. Without
appendChild, an element fromcreateElementnever appears on the page.
TL;DR: JavaScript changes the page through the DOM, a version of the page in which every tag is an object. document.querySelector("selector") grabs the first element that matches the selector (written as in CSS), or null if there is none. el.textContent = "..." replaces the element's text. el.style.color = "blue" changes its style, with property names in camelCase (style.backgroundColor). To add an element: make it with document.createElement("p"), fill in its text, then put it on the page with parent.appendChild(p). Property names must be exact, for example onclick all in lowercase. Use textContent for plain text, and innerHTML only when the text really has to be read as HTML.
⚡ Grab an element, then change it
Write:
const title = document.querySelector("h1");
title.textContent = "New Title";
title.style.color = "blue";
Guess first: if the page has no <h1>, what does title hold?
null, because no element matches. The next line fails right away: the TypeError "Cannot set properties of null".
Meaning: document is the whole page. querySelector looks for the first element on the page that matches the selector, and you write selectors as in CSS. textContent replaces that element's text, and style.color changes its colour. What you see on the page changes right away.
⚡ Property names must be exact
Write:
button.onclick = () => {
button.textContent = "Clicked";
};
Meaning: The function stored in onclick runs when its element (here button) is clicked. onclick is written all in lowercase. If you write onClick, the browser doesn't recognise it, so a click runs nothing. textContent is written with a capital C, and background-color from CSS becomes style.backgroundColor.
⚡ Make it, fill it, add it
Write:
const p = document.createElement("p");
p.textContent = "Hello from JavaScript";
document.querySelector("#box").appendChild(p);
Meaning: createElement makes a new element, here a paragraph, that you can't see on the page yet. textContent fills in its text. Only after appendChild does the paragraph go into the element #box and appear on the page.