In This Chapter
• Understand how JavaScript can be used to modify the DOM
• Meet the HTML Element
• Learn how to modify attributes
At this point, you kinda sorta know what the DOM is. You also saw how to find elements using querySelector
and querySelectorAll
. What’s next is for us to learn how to modify the DOM elements you found. After all, what’s the fun in having a giant lump of clay (or cookie dough) if you can’t put your hands on it and make a giant mess?
Anyway, besides it being fun and all, you will find yourself modifying the DOM all the time. Whether you are using JavaScript to change some element’s text, swap out an image with a different one, move an element from one part of your document to another, set an inline style, or perform any of the bazillion other changes you will want to do, you will be modifying the DOM. This chapter will teach you the basics of how to go about doing that.
Onwards!
Your ability to use JavaScript to modify what gets shown by the browser is made possible because of one major detail. That detail is that every HTML tag, style rule, and other things that go into your page have some sort of a representation in the DOM.
To visualize what I just said, let’s say you have an image element defined in markup:
<img src="images/lol_panda.png" alt="Sneezing Panda!" width="250"
height="100" />
When your browser parses the document and hits this image element, it creates a node in the DOM that represents it as illustrated in Figure 23.1.
This DOM representation provides you with the ability to do everything you could have done in markup. As it turns out, this DOM representation actually ends up allowing you to do more with your HTML elements than you could have done using just plain old markup itself. This is something you’ll see a little bit of here and a whole lot of in the future. The reason why your HTML elements are so versatile when viewed via the DOM is because they share a lot of similarities with JavaScript Objects
. Your DOM elements contain properties that allow you to get/set values and call methods. They have a form of inheritance that you read a little bit about earlier where the functionality each DOM element provides is spread out across the Node
, Element
, and HTMLElement
base types.
This hierarchy (which you’ve seen earlier) is illustrated again in Figure 23.2.
DOM elements probably even smell like an Object
when they run inside the house after rolling around in the rain for a bit.
Despite all of the similarities, for legal and...possibly health reasons, I need to provide the following disclaimer: the DOM was never designed to mimic the way Objects work. Many of the things you can do with objects you can certainly do with the DOM, but that is because the browser vendors help ensure that. The W3C specification doesn’t state that your DOM should behave identically to how you may expect things to behave with plain old Objects. While I wouldn’t lose any sleep worrying about this, if you ever decide to extend DOM elements or perform more advanced object-related gymnastics, be sure to test across all browsers just to make sure everything works the way you intended.
Now that we got this awkward conversation out of the way, let’s start to actually modify the DOM.
While you can certainly lean back and passively learn all there is about how to modify elements in the DOM, this is one of those cases where you may have more fun following along with a simple example. If you are interested in following along, we’ll be using the following HTML as a sandbox for the techniques you will be learning:
<!DOCTYPE html>
<html>
<head>
<title>Hello...</title>
<style>
.highlight {
font-family: "Arial";
padding: 30px;
}
.summer {
font-size: 64px;
color: #0099FF;
}
</style>
</head>
<body>
<h1 id="theTitle" class="highlight summer">What's happening?</h1>
<script>
</script>
</body>
</html>
Just put all of that code into an HTML document and follow along. If you preview this HTML in the browser, you will see some text appear that looks as follows:
There isn’t really a whole lot going on here. The main piece of content is the h1
tag that displays the What’s happening? text:
<h1 id="theTitle" class="highlight summer">What's happening?</h1>
Now, switching over to the DOM side of things, Figure 23.3 shows what this example looks like with all of the HTML elements (and document
and window
) mapped:
In the following sections, we’ll look at some of the common things you can do in terms of modifying a DOM element.
Let’s start off with an easy one. Many HTML elements have the ability to display some text. Examples of such elements are your headings, paragraphs, sections, inputs, buttons, and many more. There is one thing they all have in common. The way you modify the text value is by setting the textContent
property.
Let’s say we want to change the text that appears in the h1 element from our example. The following snippet shows what that would look like:
If you make this change and preview it in a browser, you will see the words Oppa Gangnam Style! show up.
Let’s look at what exactly we did to cause this change. The first step to modifying any HTML element in JavaScript is to first get a reference to it:
var title = document.querySelector("#theTitle");
Here is where our old friends querySelector
and querySelectorAll
come in. As you will see later, you also have indirect ways of referencing an element. The direct approach shown here, though, is what you will use when you have a very specific idea of what element or elements you wish to target.
Once you have the reference to the element, just set the textContent
property on it:
title.textContent = "Oppa Gangnam Style!";
The textContent
property can be read like any variable to show the current value. You can also set the property to change it to whatever you want. In this example, we are setting our textContent
property to say Oppa Gangnam Style! After this line has run, your markup’s original value of What’s happening? will have been replaced!
One of the primary ways your HTML elements distinguish themselves is through their attributes and the values these attributes store. For example, the src
and alt
attributes are what distinguish the following three img
elements:
<img src="images/lol_panda.png" alt="Sneezing Panda!"/>
<img src="images/cat_cardboard.png" alt="Cat sliding into box!"/>
<img src="images/dog_tail.png" alt="Dog chasing its tail!"/>
Every HTML attribute (including custom data-*
ones) can be accessed via JavaScript. To help you deal with attributes, your elements expose the somewhat self-explanatory getAttribute
and setAttribute
methods.
The getAttribute
method allows you to specify the name of an attribute on the element it is living on. If the attribute is found, this method will then return the value associated with that attribute. What follows is an example:
<body>
<h1 id="theTitle" class="highlight summer">What's happening?</h1>
<script>
var title = document.querySelector("h1");
alert(title.getAttribute("id"));
</script>
</body>
In this snippet, notice that we are getting the value of the id
attribute on our h1
element. If you specify an attribute name that doesn’t exist, you will get a nice value of null. The opposite of getting the value of an attribute is to actually set the value. To set the value, you would use the appropriately named setAttribute
method. You use this method by calling setAttribute
on the element that you want to affect and specifying both the attribute name as well as the value that attribute will store.
Here is an example of setAttribute
at work:
We are setting the class
attribute on the body
element to bar foo. The setAttribute
function doesn’t do any validation to ensure that the attribute you are setting is valid for the element you are setting it on. Nothing prevents you from doing something silly as follows:
The body
element doesn’t contain the src
attribute, but you can get away with specifying it. When your code runs, your body
element will sport the src
attribute...probably very uncomfortably.
There is something I need to clarify before we move on. In the examples for how to use setAttribute
and getAttribute
, I picked on id
and class
. For these two attributes, you do have another way of setting them. Because of how common setting id
and class
attributes are, your HTML elements expose the id
and className
properties directly:
<body>
<h1 id="theTitle" class="highlight summer">What's happening?</h1>
<script>
var title = document.querySelector("h1");
alert(title.id);
document.body.className = "bar foo";
</script>
</body>
In this example, notice that I switched from using getAttribute
and setAttribute
to use the id
and className
properties instead in lines 6 and 8. The end result is identical. The only difference is that you had a direct way of setting these attributes values without having to use getAttribute
or setAttribute
.
Tip
There is a much better way of setting class values besides using className
. That way is via the much more awesome classList
property that you will learn all about in the next chapter.
Tip
Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.
If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!