JavaScript, the Browser, and the DOM

by kirupa   |   17 June 2014

So far, we've looked at JavaScript in isolation. You learned a lot about its basic functionality, but you did so with little to no connection with how it ties to the real world - a world that is represented by your browser and swimming with little HTML tags and CSS styles. This tutorial will serve as an introduction to this world.

In the following sections, you will learn about the mysterious data structure and programming interface known as the Document Object Model (DOM). You'll learn what it is, why it is useful, and how it ties in to everything that you'll be doing in future tutorials.

Onwards!

What HTML, CSS, and JavaScript Do

Before we dive in and start answering the meaning of life...err the DOM, let's quickly look at some things you probably already know.

For starters, the stuff you put into your HTML documents revolves around HTML, CSS, and JavaScript. We treat these three things as equal partners in building up what you see in your browser:

what you see in your browser

Each partner has an important role to play, and the role each one plays is very different.

HTML Defines the Structure

Your HTML defines the structure of your page and typically contains the content that you see:

<!DOCTYPE html>
<html>
 
<head>
<meta content="sea otter, kid, stuff" name="keywords">
<meta content="Sometimes, sea otters are awesome!" name="description">
<title>LOL! Sea Otter! Little Kid!</title>

<link href="foo.css" rel="stylesheet"/>
</head>
 
<body>
<div id="container">
	<img src="seaOtter.png"/>
	<h1>What This Sea Otter Did to This Little Kid Will Make You LOL!</h1>
	<p class="bodyText">
		Nulla tristique, justo eget semper viverra, massa arcu congue tortor, 
		ut vehicula urna mi in lorem. Quisque aliquam molestie dui, at tempor 
		turpis porttitor nec. Aenean id interdum urna. Curabitur mi 
		ligula, hendrerit at semper sed, feugiat a nisi.
	<p>
	<div class="submitButton">
		next
	</div>
</div>
<script src="stuff.js"></script>
</body>
</html>

HTML by itself, kinda like Meg Griffin on Family Guy, is pretty boring. If you don't know who Meg is and are too lazy to Google her, here is what she looks like:

what she looks like

Anyway, you don't want your HTML documents to be boring. To transform your content from something plain and drab to something appealing, you have CSS.

Prettify My World, CSS!

CSS is your primary styling language that allows you to give your HTML elements some much needed aesthetic and layout appeal:

body {
	font-family: "Arial";
	background-color: #CCCFFF;
}
#container {
	margin-left: 30%;
}
#container img {
	padding: 20px;
}
#container h1 {
	font-size: 56px;
	font-weight: 500;
}
#container p.bodyText {
	font-size: 16px;
	line-height: 24px;
}
.submitButton {
	display: inline-block;
	border: 5px #669900 solid;
	background-color: #7BB700;
	padding: 10px;
	width: 150px;
	font-weight: 800;
}

For the longest time, between HTML and CSS, you had everything you needed to create an awesome looking and functioning page. You had structure and layout. You had navigation. You even had simple interactions such as mouse overs. Life was good.

It's JavaScript Time!

For all the great things HTML and CSS had going for them, they were both limited in how much interactivity they provided. People wanted to do more on a web document than just passively sit back and observe what is going on. They wanted their web documents to do more. They wanted their documents to help them play with media; remember where they left off; do things with their mouse clicks, keyboard taps, and finger presses; use fancy navigation menus; see spiffy (yes, I used the word spiffy) programmatic animations; interact with their webcams/microphones; not require a page reload/navigation for any kind of action; and a whole lot more:

html document and files

It certainly helped that web developers and designers (aka you and me) were itching for a way to help create these kinds of things as well.

To fill in this gap between what HTML and CSS provided and what people wanted, you had 3rd party components like Java and Flash that thrived for many years. It wasn't until recently this trend changed. There were many technical and political reasons for this shift, but one reason was that JavaScript for many years just wasn't ready. It didn't have what it took either in the core language or in what browsers supported to be effective.

That's no longer the case today. JavaScript is now a perfectly capable language that allows you to add the sorts of interactive things that people are looking for. All of these capabilities are accessed by the real star of this and the next many tutorials, the DOM.

Meet the Document Object Model (aka the DOM)

What your browser displays is a web document. More specifically, to summarize the entirety of the previous sections, what you see is a collision of HTML, CSS, and JavaScript working together to create what gets shown. Digging one step deeper, under the covers, there is a hierarchical structure that your browser uses to make sense of everything going on.

This structure is known (again) as the Document Object Model. Friends just call it the DOM. Below is a very simplified view of what the DOM for our earlier example would look like:

THE DOM!

Despite the simplicity, there are several things to drill in on that apply to all DOM structures in general. Your DOM is actually made up many kinds of things beyond just HTML elements. Everything that makes up your DOM is more generically known as nodes.

These nodes can be elements (which shouldn't surprise you), attributes, text content, comments, document-related stuff, and various other things you simply never think about. That detail is important to someone, but that "someone" shouldn't be you and me. Almost always, the only kind of node we will care about is the element kind because that is what we will be dealing with 99% of the time. At the boring / technical level, nodes still play a role in our element-centric view.

Every HTML element you want to access has a particular type associated with it, and all of these types extend from the Node base that make up all nodes:

the node hierarchy

Your HTML elements are at the end of a chain that starts with Node and continues with Element and HTMLElement before ending with a type (ie: HTMLDivElement, HTMLHeadingElement, etc.) that matches the HTML element itself. The properties and methods you will see for manipulating HTML elements are introduced at some part of this chain.

Now, before we run towards using the DOM to modify HTML elements, let's first talk about two special objects that get in the way before the road clears up for what we want to do.

The Window Object

In the browser, the root of your hierarchy is the window object. I am not using object in the generic sense where everything around you is an object. I am actually using it in the programming language sense where you have a global object called window that contains many properties and methods that help you work with your browser:

the window object

Some of the things you can do through the window object include accessing the current URL, getting information about any frames in the page, using local storage, seeing information about your screen, fiddling with the scrollbar, setting the statusbar text, and all sorts of things that are applicable to the container your web page is displayed in.

The Document Object

Now, we get to the document object. Here is where things get interesting, and it is also where you and I will be focusing a lot of our time on:

the document object

The document object is the gateway to all the HTML elements that make up what gets shown. The thing to keep in mind (and one that makes more sense as we look at future tutorials) is that the document object does not simply represent a read-only version of the HTML document. It is a two-way street where you can read as well as manipulate your document at will.

Any change you make to the DOM via JavaScript is reflected in what gets shown in the browser. This means you can dynamically add elements, remove them, move them around, modify attributes on them, set inline CSS styles, and perform all sorts of other shenanigans. Outside of the very basic HTML needed via a script tag to get some JavaScript to run in a HTML document, you can construct a fully functioning page using nothing but JavaScript if you felt like it. Used properly, this is a pretty powerful feature.

Another import aspect of the document object has to do with events. I will go into more detail on this shortly, but if you want to react to a mouse click/hover, checking a checkbox, detecting when a key was pressed, and so on, you will be relying on functionality the document object provides for listening to and reacting to events.

Conclusion

The DOM is the single most important piece of functionality you have for working with your HTML documents. It provides the missing link that ties your HTML and CSS with JavaScript. It also provides access one level up to your document and window objects

Now, knowing about the DOM is just part of the fun. Actually using its functionality to interact with your web document is the much larger and funner other part. When you are ready, head on over to the DOM section of tutorials on this site.

Did You Like This?

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out. Plus, we have a large collection of smileys you can use

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly at kirupa[at]kirupa.com.

Cheers!

Kirupa Chinnathambi

 

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Creating high-quality content is a team effort that takes a boatload of time. If you found what you see here helpful, please consider sending a small tip:

While tipping is entirely optional, we'll be your bestest friend forever if you do.

More Details & Options