JavaScript DOM Manipulation

JavaScriptJavaScriptBeginner
Practice Now

Introduction

Welcome to the JavaScript DOM Manipulation lab. The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document's structure, style, and content. When a web page is loaded, the browser creates a DOM of the page, which is a tree-like structure of objects.

In this lab, you will learn how to use JavaScript to interact with the DOM. You will practice selecting elements, changing their content, modifying their attributes, and dynamically creating and adding new elements to the page. These are fundamental skills for creating interactive and dynamic web applications.

Upon completion of this lab, you will be able to:

  • Select an element from the DOM using its ID.
  • Change the content of an element.
  • Set attributes of an element.
  • Create a new element.
  • Append a new element to the document.

Let's get started!

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 98% completion rate. It has received a 100% positive review rate from learners.

Select element by ID with getElementById

In this step, you will learn how to select an HTML element using its unique ID. The document.getElementById() method is one of the most common ways to access a specific element in the DOM.

First, locate the script.js file in the file explorer on the left side of the WebIDE. Click on it to open it in the editor. The setup script has already created this file for you.

Now, add the following code to script.js. This code will select the div element with the ID main-content and store it in a variable called contentDiv. We will then log this element to the console to verify that we have selected it correctly.

const contentDiv = document.getElementById("main-content");

console.log(contentDiv);

After adding the code, save the script.js file. To see the result, click on the "Web 8080" tab at the top of the interface. You won't see any visual changes on the page itself, but you can see the output of console.log. To do this, open the browser's developer tools (you can usually do this by right-clicking on the page and selecting "Inspect," then navigating to the "Console" tab). You should see the HTML div element logged in the console.

Console showing selected div element

Change text content with innerHTML

In this step, you will modify the content of the element you selected. The innerHTML property allows you to get or set the HTML content within an element. It's a powerful way to dynamically change what's displayed on your web page.

Continue editing the script.js file. Below the code you wrote in the previous step, add the following line. This will change the text inside the div we selected.

const contentDiv = document.getElementById("main-content");

// This line is new
contentDiv.innerHTML = "The content has been changed by JavaScript!";

console.log(contentDiv);

Make sure to save the script.js file. Now, switch back to the "Web 8080" tab and refresh the page. You should see that the text inside the box has changed from "This is the original content." to "The content has been changed by JavaScript!".

JavaScript changes div content

Set attribute with setAttribute method

In this step, you'll learn how to change an element's attributes, such as the href of a link or the src of an image. The setAttribute() method is used for this purpose. It takes two arguments: the name of the attribute to set, and the value to set for that attribute.

Our index.html file contains a link (<a> tag) with the ID labex-link. Let's change its href attribute to point to the LabEx website.

Add the following code to your script.js file.

// Select the link element
const link = document.getElementById("labex-link");

// Set its href attribute
link.setAttribute("href", "https://labex.io");

Your full script.js file should now look like this:

const contentDiv = document.getElementById("main-content");
contentDiv.innerHTML = "The content has been changed by JavaScript!";
console.log(contentDiv);

// Select the link element
const link = document.getElementById("labex-link");

// Set its href attribute
link.setAttribute("href", "https://labex.io");

Save the file, switch to the "Web 8080" tab, and refresh. Now, if you hover over the "LabEx" link, you should see in your browser's status bar that it points to https://labex.io. Clicking it will attempt to navigate to that page.

Create new element with createElement

In this step, you will create a brand new HTML element from scratch using JavaScript. This is a core part of building dynamic interfaces, where you might need to add new items to a list, display new messages, etc. The document.createElement() method is used to create an element specified by a tag name.

Let's create a new paragraph (<p>) element. Add the following code to the end of your script.js file.

// Create a new paragraph element
const newParagraph = document.createElement("p");

// Set its content
newParagraph.innerHTML = "This is a new paragraph created with JavaScript.";

// Add a class for styling
newParagraph.className = "new-element";

At this point, the element has been created in the browser's memory, but it is not yet visible on the page. We have created the element, set its content using innerHTML, and assigned a CSS class to it so it will be styled according to our style.css file. In the next step, you will learn how to add this new element to the document.

Append child element with appendChild

In this final step, you will add the element you created in the previous step to the web page. The appendChild() method adds a node (an element) as the last child of a parent element.

First, we need to select the parent element where we want to place our new paragraph. Our index.html has a div with the ID container for this purpose. Then, we will use appendChild() to add our newParagraph to it.

Add the following code to the end of script.js.

// Get the container element
const container = document.getElementById("container");

// Append the new paragraph to the container
container.appendChild(newParagraph);

Your complete script.js file should now contain all the code from the previous steps. Save the file and refresh the "Web 8080" tab. You should now see the new, styled paragraph appear below the link on your page.

Congratulations! You have successfully manipulated the DOM to change content, set an attribute, and dynamically create and display a new element.

Screenshot showing appended paragraph in web page

Summary

In this lab, you have learned the fundamental techniques for manipulating the Document Object Model (DOM) with JavaScript. These skills are essential for creating dynamic and interactive web pages.

You have successfully practiced:

  • Selecting elements from the DOM using document.getElementById().
  • Changing the content of an element using the innerHTML property.
  • Modifying an element's attributes with the setAttribute() method.
  • Creating new HTML elements in memory with document.createElement().
  • Adding newly created elements to the web page using appendChild().

By combining these methods, you can build complex user interfaces that respond to user actions and display data dynamically. Well done on completing this lab!

Morty Proxy This is a proxified and sanitized view of the page, visit original site.