• 20 hours
  • Easy

Free online content available in this course.

course.header.alt.is_certifying

Got it!

Last updated on 8/5/19

Modify page structure

Log in or subscribe for free to enjoy all this course has to offer!

Let's see how to use JavaScript to modify a web page once it's been loaded by the browser! You can then make your content more dynamic and interactive.

Example page

The examples in this chapter all use the content below. Add it to the course.html file in your file directory or follow along in the CodePen link below.

<!doctype html>
<html>

    <head>
        <meta charset="utf-8">
        <title>Some languages</title>
    </head>
    
    <body>
        <h1 class="beginning">Some languages</h1>
        <div id="content">
            <ul id="languages">
                <li id="cpp">C++</li>htm
                <li id="java">Java</li>
                <li id="csharp">C#</li>
                <li id="php">PHP</li>
            </ul>
        </div>
    </body>

</html>

Modify an existing item

You'll use what you learned in the last chapter about identifying elements in order to modify those same elements now!

HTML content

The innerHTML property can be used to change the content of an element within the DOM.
For example, you can add a new language to our list with the code below! We'll access the <ul> identified by "languages" and then add an entry to the list via an operator (+=) and an <li>.

Add the following JavaScript to the JavaScript file linked to your course HTML file, and open up the file in the browser. Alternatively, follow along on CodePen.

// Modifying an HTML element: adding an <li>
document.getElementById("languages").innerHTML += '<li id="c">C</li>';

innerHTML is often used to "empty" content. Try the following example:

// Delete the HTML content of the list, replacing it with nothing
document.getElementById("languages").innerHTML = "";

Before moving on, remove the above line from your JavaScript file. Otherwise, you'll have no content!

You should only use innerHTML to make small content changes. We'll look at more versatile solutions below.

Text content

Use the textContent property to modify the text content of a DOM element. Here is how the complete title displayed by our page.

// Modify the title's text content
document.querySelector("h1").textContent += " for programming";

Attributes

The setAttribute method sets the value of an attribute of an element. You pass the name and value of the attribute as parameters.

// Define the id attribute of the first title
document.querySelector("h1").setAttribute("id", "title");

Classes

You can use the classList property to add or remove classes from a DOM element!

var titleElement = document.querySelector("h1"); // Grab the first h1
titleElement.classList.remove("beginning"); // Remove the class "beginning"
titleElement.classList.add("title"); // Add a class called "title"
console.log(titleElement);

Add a new item

Adding a new element to a web page can be broken into three steps:

  • Create a new element.

  • Detail the element.

  • Insert the new element in the DOM.

For example, suppose you want to add the language "Python" to the list of languages on our page. Here's the JavaScript code you'd use to do so, plus a breakdown of each step:

var pythonElement = document.createElement("li"); // Create an li element
pythonElement.id = "python"; // Add details to the elment, like an id
pythonElement.textContent = "Python"; // Define its text content
document.getElementById("languages").appendChild(pythonElement); // Insert the new element into the DOM

1. Creating the element

You'd create an element using createElement (what a surprise)! This method is used on thedocument object and takes the tag of the new element as a parameter. It returns the element created as an object, which is stored in a variable called pythonElement.

2. Detailing an element

Once the element's created and stored in a variable, we add some detail to it (ID, class, text content, etc). In the example, its id becomes python and its text content becomes Python.

3. Inserting the element into the DOM

There are several techniques to insert a new node in the DOM. The most common is to call theappendChild method on the element that will be the future parent of the new node. The new node is added to the end of the list of child nodes of that parent.

In our example, the new item is added as a new child of the <ul> tag identified by "languages," after all the other children of this tag.

Variations on adding items

Determining the exact position of the new node

There is a method to more precisely define the position of inserted elements: insertAdjacentHTML. Call it on an existing element and pass it the position and a string of HTML characters that represent the new content to be added. The new content's position should be either:

  • beforebegin: before the existing element

  • afterbegin: inside the existing element, before its first child

  • beforeend: inside the existing element, after its last child

  • afterend: after the existing element

This example uses insertAdjacentHTML to add JavaScript to the beginning of the list.

// Add an element to the beginning of a list
document.getElementById('languages').insertAdjacentHTML("afterBegin",
'<li id="javascript">JavaScript</li>');

Replace or remove nodes

Replace a node

Replace a DOM element via the replaceChild method. This replaces a child node of the current element with another node. The new node and node-to-be-replaced are passed as parameters (in that order)!

The example shows replacing the Perl line with bash instead.

var bashElement = document.createElement("li"); // Create an li element
bashElement.id = "bash"; // Define its id
bashElement.textContent = "Bash"; // Define its text content
// Replace the element identified by "perl" with the new element
document.getElementById("languages").replaceChild(bashElement, document.getElementById("perl"));

Remove a node

Lastly, you can delete a node thanks to a method called removeChild, to which you'll pass the node-to-be-removed as a parameter.

// Remove the element with the "bash" id
document.getElementById("languages").removeChild(document.getElementById("bash"));

Summary

This chapter taught you how to modify the structure of a web page using JavaScript.

  • The innerHTMLtextContent, and classList properties, as well as the setAttribute method, let you modify a DOM element's information.

  • Create new DOM nodes via methods like createTextNode for, well, text nodes, andcreateElement for elements themselves.

  • The appendChild method lets you insert a new node as the last child of a DOM element.

  • The insertBefore and insertAdjacentHTML methods are alternative possibilities for adding content.

  • You can replace existing nodes with the replaceChild method or remove them withremoveChild.

  • Manipulating the DOM with JavaScript should be done sparingly so that page performance doesn't suffer.

Example of certificate of achievement
Example of certificate of achievement