Modifying DOM Elements

by kirupa   |   22 June 2014

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?

5 steps to success

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 tutorial will teach you the basics of how to go about doing that.

Onwards!

DOM Elements Are Objects...Sort Of!

Your ability to use JavaScript to modify what gets shown by the browser is made possible because one major detail. That detail is that every HTML tag, style rule, and other things that go into your page has 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:

from markup to the DOM

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 saw a little bit about earlier where the functionality each DOM element provides is spread out across the Node, Element, and HTMLElement base types:

the node hierarchy

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.

Let's Actually Modify DOM Elements

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 into an HTML document and follow-along. If you preview this HTML in the browser, you will see something that looks as follows:

what's happening

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, this is what this example looks like with all of the HTML elements mapped:

The DOM Tree for this HTML

In the following sections, we'll look at some of the common things you can do in terms of modifying a DOM element.

Changing an Element's Text Value

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:

<body>
    <h1 id="theTitle" class="highlight summer">What's happening?</h1>

    <script>
        var title = document.querySelector("#theTitle");
        title.textContent = "Oppa Gangnam Style!";
    </script>
</body>

If you make this change and preview in the browser, you will see the following:

gangnam style

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, thuough, 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 like we are here to change the value that is stored currently. After this line has run, your markup's original value of What's happening? will be replaced in the DOM by what you specified in JavaScript.

Attribute Values

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 image 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 the properties the DOM provides. 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. Below 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:

<body>
    <h1 id="theTitle" class="highlight summer">What's happening?</h1>

    <script>
        document.body.setAttribute("class", "bar foo");
    </script>
</body>

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:

<body>
    <h1 id="theTitle" class="highlight summer">What's happening?</h1>

    <script>
        document.body.setAttribute("src", "http://www.kirupa.com");
    </script>
</body>

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. 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.

For Setting Class Values, use classList

There is a much better way of setting class values besides using className. That way is via the much more awesome classList property that I cover in great detail in the Using the classList API tutorial.

But Wait...There is More!

It may seem a bit odd to end our discussion around modifying DOM elements at this point. While changing an element's text and attribute values are very popular, they are by no means the only major kinds of modifications you will perform. The reason for ending at the cliffhanger is because manipulating the DOM and using an element's properties and methods to accomplish our task is central to everything we are going to be seeing. In subsequent tutorials you are going to see a whole lot more of what you've seen here.

Your main takeaway from this tutorial is that the DOM changes you perform will almost always take one of the following two forms:

  1. Setting a property
  2. Calling a method

The textContent, setAttribute, and getAttribute approaches you saw here cover both of those approaches. You'll see this come up with our next tutorial around Traversing the DOM.

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

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 via e-mail, facebook, or twitter.

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!