A Beginner's Guide to DOM Manipulation

A Beginner's Guide to DOM Manipulation

Before diving deep into DOM manipulation, let me give you a brief introduction to DOM(Document Object Model).

What is DOM?

Now, you must have come across this term in your web development journey. Am I right? Never mind, let me tell you guys about DOM and DOM manipulation. DOM is a programming interface that allows us to create, change or remove elements from a web document - such as HTML.

DOM Tree

The structure of DOM is represented by what we call a ‘node tree’. In this node tree, the elements form the root node, which in turn has branches containing children nodes of elements nested within it. The tree will grow until it reaches an element that has no element nested in it.

DOM Manipulation

DOM manipulation is when you use JavaScript to add, remove and modify elements of a website. This is a very common concept in web development.

A basic use case of DOM manipulation is a to-do app. When you enter a task in an input field and click on add button, the task gets added to the to-do list. Now suppose, there is a filter containing these three categories - all tasks, completed tasks, and incomplete tasks. As you click on any of the filters, the no of tasks in the to-do list changes automatically as per the category. This is all possible due to DOM manipulation.

Consider this HTML document, we will be performing DOM manipulation on it:

<!DOCTYPE html>
<html lang = "en">
    <head>
        <title>
            DOM Manipulation
        </title>
    </head>
    <body>
        <h1 id="welcome-msg">
            Welcome to my blog!
        </h1>
        <p>
            Do you know about DOM manipulation?
        </p>
        <p>
            If you don't, you will learn a lot about that in this blog!
        </p>
        <div>
            <p> A new para will be inserted here </p>
        </div>
        <button id="my-btn">
            Click Me!
        </button>
    </body>
    <script>
    </script>
</html>

Selecting elements in the DOM

To manipulate an element inside a DOM, you first need to select it and store a reference to it inside a variable. You can achieve this by using the Query Selectors as follows : (Put this code in the script tag i.e. inside )

const list = document.querySelector('ul');
const items = document.querySelectorAll('li');

The querySelector() method returns the first element within the document which matches a specified CSS selector(s). Whereas, the querySelectorAll() method returns all the elements within the document which match the specified CSS selector(s). This method returns a node list.

Note: In the querySelector() method, select an element by classname using the .(period) symbol in front of classname and select an element by id, using the #(hashtag) symbol in front of id.

We can also access the elements using their id, class, and tag. These are some of the old methods, the latest being the querySelector() as discussed above.

const a = document.getElementById("the id")
const b = document.getElementsByClassName("the classname")
const c = document.getElementsByTagName("p")

Styling an element

After we know how to select the elements in the DOM, now it's time to see some magic unfold. You can style these elements as shown below

const heading = document.querySelector("#my-heading")
heading.style.backgroundColor = "red"
heading.style.color = "white

In this example, the background color of the heading is changed to red, and the color(text color) is changed to white.

Creating elements

Now let’s move forward to creating an element. You can create an element by writing the code as shown below :

const para1 = document.createElement('p')
para1.textContent = "I am new to this thing"

Here, we have created a new paragraph element using createElement() method and added some text content to it using the ‘textContent’ property.

Adding elements

After we have created an element, we can also add this element to the DOM using DOM manipulation. Firstly, we need to select the parent element

const div = document.querySelector('div')

To add the ‘para1’ element at the end of the section element, use the appendChild() method:

div.appendChild(para1)

Modifying Text

We can also modify the text content of a particular element. This can be achieved by either of the following properties:

const p1 = document.querySelector('p')
p1.innerText = 'Some text'
p1.textContent = 'Some text'
p1.innerHTML = '<span style="color:red">Task List</span>'

Removing an Element

There will be times when you want to delete some nodes from the DOM. Well, we can also achieve this by DOM manipulation.

We will now delete the 'para1' node that we created above. This is done by using the removeChild() method and remove() method as shown below

div.removeChild(para1)

removeChild() method is used when we know the parent node of the particular node that is to be deleted.

para1.remove()

remove() method is used to remove an element or node by itself from the document.

Modifying Elements Attributes & Classes

We can also change & set the attribute of a particular tag. Attributes are the properties of an HTML tag.

const img = document.querySelector('#myImage')
img.src = "tiger.jpg"

The above piece of code will change the image.

div.setAttribute('class', 'container')

The above code sets the class attribute of the section to container.

Event Listeners

Let us now add an event listener to our button element to display a “Hello World!” message when clicked. We will do this by using the addEventListener() method.

This method takes in two parameters, the first parameter is the type of event, which in our case is “click” and the second is a callback function.

const btn = document.querySelector('#my-btn')
btn.addEventListener("click", function(){console.log("Hello World!")})

Make sure you open your console window to check the output 🙂

Conclusion

DOM manipulation is the heart of the modern, interactive web and all the above methods and properties can be used to manipulate the DOM.

I hope you enjoyed reading this blog. Please share your valuable thoughts in the comment section.

Follow me on Twitter: twitter.com/imsunilballani

Connect with me on LinkedIn: linkedin.com/in/sunil-ballani-17b31b200