Evan X. Merz

gardener / programmer / creator / human being

What is the DOM?

In this post, I'm going to introduce the Document Object Model, which is better known as the DOM.

TLDR: The DOM is the way a webpage is represented within a browser

The DOM is a bit of structured data that holds a representation of a webpage in order to enable programs to be able to manipulate it.

It's a bit like a 3d model that you might use in a 3d printer. The 3d printer is the display device, like a web browser. The 3d model is needed by the 3d printer for it to be able to do anything. You can manipulate the 3d model to make the 3d printer do what you want.

Why should we care about the DOM?

Why does the DOM matter? Can't we go about writing web code without knowing about the DOM?

The DOM matters because it is the representation of a web page that we can work with in JavaScript. It's true that, as a web programmer of over twenty years now, I have probably explicitly thought about the DOM only a handful of times. But I use it every day, and in the dark ages of JavaScript, we had to work with it very directly. These days we use packages like React or jQuery to wrap add a convenient layer of abstraction above the DOM. Still, in this post I'm going to show you how to use the DOM the old fashioned way.

This is still very important to know because occasionally you do have to do it, even when using the modern libraries for interacting with the DOM.

Finding elements in the DOM in JavaScript

In JavaScript, the DOM is stored as a global variable named "document". So when you want to do something with the DOM, you use the document variable.

One of the things you must be able to do is find the HTML element that you want to work with. The document gives us several handy methods to find elements by their id or class attributes. The getElementById method returns the first element found with the matching id attribute. Since id attributes should be unique, this should be the only element with that id in the document.

So to find a document with the id "elephant", you'd use the following line of code.

let elephantElement = document.getElementById("elephant");

This line of code contains a few things that might look unfamiliar to anyone who hasn't used JavaScript before. Here's a diagram that breaks it down.

A diagram that breaks down a line of JavaScript that calls document.getElementById

The word "let" is a reserved word that indicates that the next word is a locally scoped variable. Don't worry if you don't know what "locally scoped" means. In this case, it just means that it's not a global variable, like document. Then the word "elephantElement" is the variable name, and the equals sign indicates that whatever is returned by the expression on the right should be stored in the variable on the left.

The id attribute isn't the only way to find elements. JavaScript also specifies a way to get elements with the same class attribute using the getElementsByClassName method. Notice that "Elements" is plural because the method returns an array, as many elements may share a class.

let elephantElements = document.getElementsByClassName("elephant");

The structure of this line of code is essentially the same as the previous one. The only difference is the name of the method that is called, the name of the variable, and the type of the variable.

How to modify a webpage using JavaScript

You can also use JavaScript to change the content of a webpage. When you've located the element you want to change, you can use the innerHTML method to get or set the content of that element. Like much of the JavaScript in this post, this is considered a bad thing to do these days. Typically you'd use the methods in a UI framework like React to mutate the page.

let elephantElement = document.getElementById("elephant");
elephantElement.innerHTML = "Is this an elephant?"

You can also add elements to the page using the createElement and append methods. This blurb appends a copyright notice to a blog post.

let blogPost = document.getElementById("post");
let copyrightNotice = document.createElement("p")
copyrightNotice.innerHTML = "Copyright " + new Date().getFullYear() + " by the author";
blogPost.append(copyrightNotice);

Let's put that into a real HTML file to see it in action. Here's the full example. If you've typed it in correctly, then you should see a copyright notice at the bottom of a paragraph of latin.

<!DOCTYPE html>
<html>
  <head>
    <title>How to modify the DOM using JavaScript</title>
  </head>
  <body>
    <div id="post">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>
    <script>
      let blogPost = document.getElementById("post");
      let copyrightNotice = document.createElement("p")
      copyrightNotice.innerHTML = "Copyright " + new Date().getFullYear() + " by the author";
      blogPost.append(copyrightNotice);
    </script>
  </body>
</html>

Summary

The DOM is the internal model of a webpage stored in the web browser. It can be manipulated using JavaScript methods such as getElementById, innerHTML, and append.

More

Introduction to JavaScript

In this post, I'm going to introduce the JavaScript programming language and show you a few ways it's commonly used on the web.

WARNING: Some prior programming required!

I'm not introducing programming in general. This isn't a good first tutorial for someone who has never written a line of code in their life. I'm assuming that you know what functions are, and that methods and subroutines are the same thing. I'm assuming that you've written at least a little of some kind of code in the past.

TLDR: JavaScript is the engine of a webpage

HTML is used to define the structure of a web page. CSS defines the look and feel of a page. JavaScript defines how a page acts and responds to user input.

If a web page is a car, then HTML is the frame, CSS is the body, and JavaScript is the engine.

A haiku about JavaScript

Dearest Javascript,

You are my favorite tool

that costs me nothing.

Why not Java?

JavaScript has nothing to do with Java. The name JavaScript came about as an attempt to steal some of the hype around the Java programming language in the 1990s. In the 30 years since then, their positions have entirely flipped, with JavaScript now being the programming language that sees tons of innovation and market support, while Java is withering. Why has this happened? Why has JavaScript been so successful?

In my opinion, Java has been uniquely unsuccessful as a language because it has refused to grow and innovate. Java set some standards and some conventions for the language, and even thirty years later, the committees who guide specification for that language continue to be far too conservative.

If you're a Java programmer and you don't agree with me, then I encourage you to try Microsoft C#. That's the fun language that Java could have been.

And why is that?

C# and JavaScript have become incredibly open-ended. You can write code in lots of different ways, using features borrowed from other cool languages and frameworks. Both are sort of like Frankenstein's monster inasmuch as they are collections of mismatched parts that come together to form a surprisingly intimidating beast.

And this scares some people.

But, much like Shelley's actual monster, they are actually quite nice, and I hope to convey that to you in this introduction.

But what is JavaScript?

It's a programming language that runs in the web browser and on nearly every device that exists. On a webpage, you include JavaScript within the script element, or by including code in an external file. There's more to it than that, but let's learn by doing.

A JavaScript function

One of the key responsibilities of JavaScript is to respond to user input. Beside a few basic interactions, like clicking a link or a dropdown, every action that occurs on a webpage is handled by custom event handlers that are usually written in JavaScript. In this case, we're going to write a script that handles a click event.

When the user clicks on something, the browser creates what is called a click event. It then runs a bit of code called a function that is tied to that event. Here's the click handler function that we're going to write.

function showWarningOnClick() {
  alert("Warning! The elders of the internet have been notified!");
}

That might look like nonsense to you, so let's break it down. This graphic shows how each of the pieces come together.

A javascript function

The first line is the function declaration. The word "function" declares that the next word is the name of a function. So "showWarningOnClick" is the name of the function. The parentheses, "()", would enclose the method arguments, if we needed any. The open bracket, "{", indicates that the next line will be the first line of the function body.

The second line is the actual code that is executed by this function. In this case, it calls another function. It calls "alert", with the argument "Warning! The elders of the internet have been notified!". Notice that the argument is enclosed with parentheses. Then the line ends with a semicolon. Most lines of JavaScript code must end in a semicolon.

That's the code that we will run when a button is clicked. We will see in the next section how we can trigger that function using a button.

A JavaScript event

The following line of code creates a button and adds a handler for the onClick event.

<button onClick="showWarningOnClick();">Don't click me</button>

Notice that the button isn't created using a div or span element, as you might expect. When creating buttons, it's good to use the button element if you can. This element is friendly to screen readers, and other accessibility technology.

The only attribute given is "onClick", and it's set to call the function that we defined earlier. The onClick attribute tells the browser what to do when the button is clicked.

It's important to note that onClick events can be attached to any elements. They aren't something unique to buttons. You can attach methods to the onClick attributes of divs or spans, or any other HTML elements.

Responding to a click event in JavaScript

So let's put it all together. The code should look something like this. And as a reminder, please type this in, don't copy paste it. The point is to learn, and you will learn and remember more if you type it out.

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Hello World</title>
    <script>
      function showWarningOnClick() {
        alert("Warning! The elders of the internet have been notified!");
      }
    </script>
  </head>
  <body>
    <div>
      <button onClick="showWarningOnClick();">Don't click me</button>
    </div>
  </body>
</html>

When you run it, by double clicking it and opening it in a web browser, you should see a single button in the upper left that says "DOn't click me". Click it, and you should see a little popup with the message "Warning! The elders of the internet have been notified!".

Summary

JavaScipt is a fun, open-ended programming language that is particularly useful in web browsers. In this post we learned about JavaScript functions and event handlers.

More

Here are some other introductions to JavaScript from around the web. I suggest that you spend time to check them out, even if you found this really easy. It's good to go over the fundamentals often, and it's particularly good to get multiple perspectives.

Other useful HTML elements

In this post, I'm going to introduce some HTML elements that are still useful in the modern web development, even if they aren't used as often as div or span.

TLDR: These HTML elements are useful for accessibility and search engine optimization

You can build most webpages using only div and span elements, along with the structural elements html, head, and body. However, it's important to know about other elements if you want your page to rank highly in Google search results, or you want your page to be accessible to people with disabilities.

Headings and titles

Heading elements are used to show titles or subtitles. They are important to your visitors because they make text more readable. They are important to Google because Google uses them to understand the content of your pages.

Heading elements are h1, h2, h3, h4, and h5. The h1 element is the top level title of the page, and should only occur once on a page, otherwise Google Search Console will show a warning for that page, and you won't rank as highly in web searches.

Here's an example of an h1 element.

<h1>I'm a page title that can be seen by the visitor</h1>

It's important to note that there IS an actual title element in HTML. When the title element appears in the header, it is used to set the text that is shown in the tab of your web browser.

<title>This is the text at the top of the tab</title>

Paragraphs in HTML

Before CSS was invented and standardized, there were lots of HTML elements used to format text. You can still use some of these, but it is widely discouraged. The "b" element bolds the enclosed text. The "i" element applies italics to the enclosed text. The "br" element adds a newline. You should never use any of those elements, but there is one element that is still quite useful.

The "p" tag is used to enclose a paragraph of text. It is useful as something separate from a div because it includes useful browser default styles, and because it serves as a good way to style the body text for your page.

<p>I'm a paragraph with some nice browser default styles.</p>

Browser defaults are a complex and controversial topic. Each browser starts with its own set of default styles so that a basic HTML page will be readable. There are many modern packages that override or eliminate these styles so that they don't interfere with a site's custom styles. I don't have a strong opinion on browser defaults in either direction.

Lists in HTML

Lists are another bit of semantic HTML that are still widely used. There are two types of lists in HTML, ordered lists and unordered lists. These can be represented by the "ol" and "ul" elements respectively. List items can be represented by the "li" element.

So what's the difference between the two list types? Ordered lists are numbered, while unordered lists are bulleted.

<ol>
  <li>First item</li>
  <li>Second item</li>
</ol>

If you drop that into an HTML file then you will see something like the following.

Screenshot of an ordered list in HTML.

I encourage you to replace the "ol" elements with "ul" and see what happens.

Nav, main, and footer elements in HTML

Finally, I want to recommend using the elements nav, main, and footer. These elements are used to encapsulate the navigation portion of the page, the main content of the page, and the footer of the page. These elements are absolutely VITAL for accessibility, as they tell screen readers about which part of the page they are reading. You need to remember accessibility for two reasons. It is important to allow as many people as possible to access your site, and Google will penalize you if you don't.

They are used just like divs.

<nav>
  <ul>
    <li>Menu item 1</li>
    <li>Menu item 2</li>
    <li>etc</li>
  </ul>
</nav>

Project: Personal web page

This post contains the first assignment in my free web programming course.

Project: Personal web page

Now that you know a little html and css, you should be able to produce some simple web pages. In this assignment, I want you to create a web page about yourself. It should be pretty similar in content to my about-me page on my website, but it should be about you and the things you like.

Here's what it must contain.

  1. A title that says your name and is styled like a title.
  2. A picture of you or something you like.
  3. A short paragraph of at least three sentences. You can use Lorem Ipsum if you can't write three sentences about yourself.
  4. A quote you like that is styled like a quotation. Usually quotes are indented more and displayed in italics.
  5. At least three links to things you've done or things you like. Use html lists to show these.

Introduction to CSS

In this post, I'm going to introduce CSS, and demonstrate how it can be used to apply styles to a web page.

TLDR: CSS defines the look and feel of a web page

After building the structure of a page using HTML, you can add styles to HTML elements using CSS. If HTML is a car's frame, then CSS is the body shape, the paint job, and the rims.

What is CSS?

CSS stands for Cascading Style Sheets. Programmers and web designers use CSS to describe the colors, fonts, and positions of HTML elements. Web browsers interpret the CSS on a page to show those styles to viewers.

CSS can be added to an HTML document in multiple ways. It can be added directly to HTML elements using inline styles, it can be added to the head section using style elements, or it can be included from another file.

A simple inline css example

Here's an example of a very simple use of inline css using the style attribute on an element. All it does is set the font color to blue.

<div style="color: blue;">This text should be blue.</div>

To try this in your own html file, just type that code within the body section of the page. If you did it right, then the text should appear blue.

There are three important parts of this inline css. The first is the style attribute on the div element. Use the style attribute to apply inline styles. The second is the word "color", which specifies which property of the element that should be styled. The third important bit is the word "blue", which specifies the color. There are many ways to specify colors in CSS, and using names is the simplest.

An inline CSS style attribute.

I'm introducing inline styles here because they are useful for debugging, however, inline styles are impractical for a number of reasons, so we're going to look at a few other ways of incorporating CSS into an HTML document.

A simple CSS style element example

CSS styles can also be included in a document using the HTML style element. Usually such styles are placed in the head section of the document.

Using the HTML style element like this is generally discouraged, however, because the styles are not reusable in other documents. That's why styles are usually stored in separate files that can be included in any HTML document.

It's good to know about style elements, however, because they are sometimes used in emails. When creating a beautiful email, you don't have access to other files, so style elements are sometimes the best option.

<style>
  span {
    background-color: red;
  }
</style>

This CSS rule sets the background color to red for all span elements on a page. Here's how it might look in a full HTML document.

<!DOCTYPE html>
<html>
  <head>
    <title>Divs and spans</title>
    <style>
      span {
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div>
      This is a div and <span>this is a span</span>.
    </div>
    <div>
      Notice that <span>all span elements on the page receive the style indicated in the rule above</span>. This is due to how CSS selectors work.
    </div>
  </body>
</html>

Here's a graphic showing how that style breaks down into parts. The selector is used to select which elements will recieve the style. The property and value describe the style to apply, just like when using inline styles.

A visual breakdown of a CSS rule.

Here's a nice post about styling emails if you want to dig deeper. This author prefers using inline styles.

What are selectors?

The problem with inline CSS is that it clutters up the code for your webpage, and it's not reusable. A single style declaration can be twenty or more lines long. That's a lot to insert into an HTML element, and adding it makes the code difficult to read. Also, inline styles only apply to the element they are on. If you want to use an inline style twice, then you have to duplicate it, which is a big no-no in programming. Fortunately, there are other ways to write CSS.

CSS can be included in a "style" HTML element. CSS written in the style element uses syntax called "selectors" to apply styles to specific elements on a page.

For example, say you wanted all span elements on your page to have a larger font. You might include something like the following in the head section of your HTML document.

<style>
  span {
    font-size: 2em;
  }
</style>

That selector selects all elements with a given tag name. You could use "div" to style all divs, or "h1" to style all h1 elements. But what if you want to be more specific what if you only want to style some elements of a given type?

If you want to be more specific, then you can add class or id attributes to your html, then use those attributes in your CSS selectors.

Here's an example that shows a class attribute on a div and a selector that uses the class value. Notice that the class name is preceded by a period in the selector.

<style>
  div.blueText {
    color: blue;
  }
</style>
<div class="blueText">This text should be blue</div>

Here's an example that shows how to use the id attribute and selector. Notice that the hashtag symbol precedes the id in the css selector

<style>
  #blueText {
    color: blue;
  }
</style>
<div id="blueText">This text should be blue</div>

Usually class is used when you want to have many things that share the same style. The id attribute is used when you are styling something that is unique on the page.

Including CSS in a separate file

Inline styles and style elements are not the most common way of including styles in a web page. Usually styles are imported from a stylesheet file that contains CSS and ends with the .css extension.

Type the following code into a file named css_example.css.

span.blue {
  color: blue;
}
span.red {
  color: red;
}
#title {
  font-size: 2rem;
}

Now type the following code into a file named css_example.html.

<!DOCTYPE html>
<html>
  <head>
    <title>CSS Example</title>
    <link rel="stylesheet" href="css_example.css">
  </head>
  <body>
    <h1 id="title">This is a large title</h1>
    <div>
      This is a div with <span class="red">red text</span>.
    </div>
    <div>
      This is another div with <span class="blue">blue text</span>.
    </div>
  </body>
</html>

If you did it all correctly, then you should end up with something like this, when opened in a web browser.

Image showing the result of css example 01

What are all the CSS properties?

CSS can be used to style just about any aspect of an HTML element. With CSS you can create shadows, animations, and nearly anything else you see on the web. In my posts I'm going to focus on the most common CSS properties, but if you want to see the complete list of things that can be styled with CSS, then check out MDN's comprehensive list of CSS properties.

Summary

  1. CSS is the style layer of the web.
  2. CSS is usually imported into an HTML file from a separate CSS file.
  3. The element, class, and id selectors allow you to target your styles to specific elements.

More

CSS is quite large and complex, but you don't have to know everything about it to use it effectively. You only need to know the fundamentals, and be able to use web search to find the other stuff.

Previous page | Next page