Working with the DOM

This section of the guide will cover how JavaScript can be integrated with HTML and CSS to add functionality and interactivity in a page. We'll take a look at the DOM(Document Object Model), events, how to query and manipulate the DOM, and end with fetch requests.

The DOM

DOM stands for Document Object Model and is a way of structuring an html document as a tree. This makes it easier for the browser to update the document's styling and when JS is applied.

Take the following html document:

<!DOCTYPE html>
<html>
   <head>
       <link rel="stylesheet" href="styles.css">
       <title>My web page</title>
   </head>
   <body>
       <h1>Hello world</h1>
       <button onclick="alert('Hello!')">Say hello</button>
   </body>
</html>

This html document is converted into a tree like the one below:

It is not important to know how this is done, but it is important to understand that every html document is converted into this model by the browser to allow for easy querying and updating of the elements.

Events

Events are, quite literally, "things that happen". In this context, they are "things that happen to element(s) on the page". Examples of events are "click", "hover" and "keyup" (when the user presses a key and lets go, letting the key come up).

Events attributes can be assigned to html elements to execute some JS code when the event occurs. Take an example from the above html:

<button onclick="alert('Hello!')">Say hello</button>

This sets an onclick attribute for the button; this means when the button is clicked, the JS code is executed. In this case, the code is alert('Hello!'), so when the button is clicked, the user gets a popup with the text "Hello!".

There is a full list of JS events here.

Next steps

Copy the above html into a separate html file and save it with a name of your choice. Then add some CSS of your choice, or reuse the styles.css file from the previous section. You can even go in with a combination of the two, and define some additonal styles in a separate CSS file, then import both files into the html file.

For the next few sections we'll look at querying the DOM from the Browser Console.

Last updated