Skip to main content

JavaScript

To make our content interactive, we use JavaScript.

Links:

Browser console​

You will need to enable the developer console. Follow the instructions for your browser.

https://developer.chrome.com/docs/devtools/console

You can open the console with âŒĨ⌘J.

Inserting JavaScript​

We insert JavaScript with a <script> tag. You can put JavaScript directly inside the <script> tag, but usually you want to put it in a separate file, and include it via the src attribute.

To see this message, open up your browser console. console.log() is to help you in debugging your own code, not for communicating with your users.

Let's log some other data types:

Notice that 4 appears in two different colors depending on whether it is the string "4" or the number 4! Although JavaScript implicitly converts between these in some situations, it is important to understand the difference.

A common pattern in JavaScript is

console.log({ myVariable });

to log the value of a variable. This is logging the object {"myVariable": myVariable}. This is better than just doing console.log(myVariable) since it also includes the name of the variable in the log.

DOM​

The DOM is how JavaScript code interacts with HTML documents. We can select existing elements on the page, create new elements, and modify existing elements (e.g. by adding children).

Selection methods

These are the ones you'll use most often, which let you find either the first or all elements matching a CSS selector:

Beware that for historical reasons, querySelectorAll() returns a weird type instead of an array. So you'll often want to write Array.from(document.querySelectorAll(...)).

Some other selection methods you may encounter:

Creation methods

Manipulation methods

Refactoring​