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.
Chrome
Firefox
Safari
https://developer.chrome.com/docs/devtools/console
You can open the console with âĨâJ.
https://firefox-source-docs.mozilla.org/devtools-user/web_console/
You can open the console with âĨâK.
First you must enable developer features. Then you can open the console with âĨâC.
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:
document.querySelector()andElement.querySelector()document.querySelectorAll()andElement.querySelectorAll()
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:
-
document.getElementsByClassName() -
document.getElementById() -
document.getElementsByTagName() -
Element.closest()
Creation methods
-
document.createElement() document.createElementNS()â you need this for creating SVG elements, otherwise ignore it-
document.createTextNode()
Manipulation methods
-
Element.after() -
Element.append() -
Element.before() -
Element.getAttribute() -
Element.hasAttribute() -
Element.prepend() -
Element.remove() -
Element.replaceWith() -
Element.setAttribute() -
Element.removeAttribute()