Introduction to DOM Manipulation with Javascript

Introduction to DOM Manipulation with Javascript

Javascript’s DOM Manipulation: Key to Interactive Web Design


The goal of this article is to introduce the concept of the DOM (Document Object Model) and how to manipulate it using JavaScript. You will learn how to use some of the most common methods and properties, such as: getElementById , createElement , appendChild , insertBefore , removeChild , replaceChild , innerHTML , style , classList , addEventListener to create, modify, and delete elements in an HTML document. You will also see how to use CSS to style the elements and how to add interactivity with a button. By the end of this article, you will have a better understanding of how the DOM works and how to use JavaScript to manipulate it.


Understanding the DOM

The DOM stands for Document Object Model, and it is a way of representing the structure and content of a web page as a tree of objects. Each object corresponds to an element, attribute, text, or comment in the HTML or XML document, and has properties and methods that you can use to change it.

Document Object Model, as the name suggests - is a model of a document that is composed of objects. An interface that allows a programming language (such as JS) to access and manipulate the structure, content, and styling of a document using objects.

There is a special object in the DOM called the document object that represents the entire HTML document that is loaded in a web browser. It is the root node of the document tree, which means it has no parent node, and has many properties and methods. For example, you can use the document.title property to get or set the title of the document. You will learn more about the document object, its methods and properties, and how to use it with JavaScript as you read along!


Let's start by creating a basic HTML file:

<!DOCTYPE html>
<html>
    <head>
        <title> 
            DOM Manipulation Demo 
        </title>
    </head>

    <body>

    </body>
</html>

Next, I've added some content to the body:

<body>
  <h1 id="title">DOM Manipulation Demo</h1>
  <div id="container">
    <p id="intro">This is a simple web page that demonstrates
         how to use JavaScript to manipulate the DOM.</p>
    <p id="result"></p>
  </div>
  <button id="btn">Click Me</button>
</body>

A little bit of styling:

body {
     background-color: antiquewhite;
    }

h1 {
    color: blue;
    }

p {
    color: green;
   }

This is how it looks:


Interacting with the DOM

getElementById

Now, let's start with the most basic and most used method: document.getElementById(id) - This method returns the element that has the specified id attribute in the document. For example, document.getElementById("demo") will return the element with id=“demo”.

Let's get all the elements in the body using this method and assign them to variables like so:

<script>
// Get the elements by id
var title = document.getElementById("title");
var container = document.getElementById("container");
var intro = document.getElementById("intro");
var result = document.getElementById("result");
var btn = document.getElementById("btn");
</script>

createElement

How about we create a new element?

document.createElement(tagName) - This method creates a new element with the specified tag name and returns it. For example,

// Create a new element
var newP = document.createElement("p");
newP.innerHTML = "This is a new paragraph created by JavaScript.";

innerHTML

element.innerHTML - This property gets or sets the HTML content of the

element. For example, we set the content of the newly created p element using this property.

appendChild

Now, let's add this new element to the container. For that, we'll use the method - element.appendChild(child).This method adds a new child element, p to the end of the specified parent element, container.

// Append the new element to the container
container.appendChild(newP);

insertBefore

Let's create another element and add it before intro.

// Insert a new element before the intro
var newH2 = document.createElement("h2");
newH2.innerHTML = "Subheading";
container.insertBefore(newH2, intro);

Here, we have used another basic method - element.insertBefore(newChild, referenceChild) This method inserts a new child element (h2or newH2) before the specified reference child element (intro) in the parent element (container)

removeChild

Now just for fun, let's remove an element:

// Remove the result element
container.removeChild(result);

As you might have already guessed, element.removeChild(child) removes the specified child element (result) from the parent element (container).

replaceChild

Next, let's replace title with a new one:

// Replace the title element with a new one
var newH1 = document.createElement("h1");
newH1.innerHTML = "New DOM Manipulation Demo";
document.body.replaceChild(newH1, title);

element.replaceChild(newChild, oldChild) - This method replaces the specified old child element (title) with the new child element (h1) in the parent element.

addEventListener

Now, let's see how we can interact with a button:

// Add an event listener to the button
btn.addEventListener("click", function() {
// Change the style of the container
container.style.backgroundColor = "yellow";
container.style.border = "solid red 2px";
container.style.padding = "10px";

// Change the class of the new paragraph
newP.classList.add("highlight");

// Change the innerHTML of the new heading
newH1.innerHTML = "You clicked the button!";
});

We are calling a method that adds an event listener to the button element.

An event listener is a function that is executed when a certain event occurs on an element. For example, when you click on a button, a click event is triggered on the button element.

As you can see, an event listener can be added to an element (in our case, it's a button) using the addEventListener method, which takes two parameters - the name of the event (click) and the function to execute when the event occurs (callback function).

Now, let's see what is happening in our callback function:

style

container.style.backgroundColor = "yellow";
container.style.border = "solid red 2px";
container.style.padding = "10px";

The style property allows us to access and modify the CSS properties of an element using JavaScript. For example, we can change the background color, border, and padding of an element using the style.backgroundColor, style.border, and style.padding properties, respectively.

classList

newP.classList.add("highlight");

The classList property has a method add that can be used to add a new class name to an element. For example, the statement newP.classList.add("highlight") adds the class name “highlight” to the new paragraph element.

newH1.innerHTML = "You clicked the button!";

Lastly, we are using the innerHTML property to replace the content of an element, newH1with a new one - "You clicked the button!".

Recap

In this article, we covered some of the basic JavaScript methods to manipulate the DOM. To summarize:

  • document.getElementById(id) - to get an element by its id attribute

  • document.createElement(tagName) - to create a new element with a given tag name

  • element.appendChild(child) - to add a new child element to the end of a parent element

  • element.insertBefore(newChild, referenceChild) - to insert a new child element before a reference child element in a parent element

  • element.removeChild(child) - to remove a child element from a parent element

  • element.replaceChild(newChild, oldChild) - to replace a child element with a new one in a parent element

  • element.innerHTML - to get or set the HTML content of an element

  • element.style - to access or modify the CSS style of an element

  • element.classList - to access or modify the class names of an element

  • element.addEventListener(event, callback) - to add a function that is executed when an event occurs on an element


You can experiment with different ways of using the DOM to create amazing web pages. The possibilities are endless!

I hope you enjoyed this article and learned something new. If you have any questions or feedback, feel free to leave a comment below. Thank you for reading and happy coding!