Before we learn about DOM manipulation, it is important to know what exactly is a DOM. In simple terms, DOM(Document Object Model) is an interface that is created by the browser representing the HTML document in a node object.
The DOM is created in a tree-like structure where each element is a node. It acts as a middle man between HTML and JavaScript and helps JS to interact with the HTML document using different methods and properties.
Working with the DOM
In this blog, we will be going over a few of the things that you can do with DOM and how you can manipulate it using different methods.
1. Get the element
2. Make changes
3. Create a new element
4. Append
Getting the Elements
If we want to change or manipulate an Element, the first thing we need to do is “get” the element in our JS file. We can do that my calling the following methods with the correct attribute in the argument.
- .getElementsByTagName()
- .getElementsByClassName()
- .getElementsById()
- .getElementById()
- .querySelector()
- .querySelectorAll()
The first 3 methods return an HTMLCollection of the selected element with the specified attribute. Among these, the querySelector is probably my favorite one to use. It can grab any type of attribute/tag, hence more reusable. But since the querySelector is more general we need to use the correct selector for that attribute.
Making changes in the document
What do we need to change and where? Let’s say we want to change a new heading. First, we would select the element we want to change/add. We can do that by using one of the above methods, I will use the querySelector method.
Now that we got the element, we can change its content by using either .innerHTML or .textContent property. For this example, I’ll be using .innerHTML- it gets access to the text inside of our selected tag.
Creating Elements
We can not only edit but also add new elements to it. To do that we use the .createElement method. Let’s say we want to create a subheading tag inside of the body, we can do selecting where we want to create the new element, calling the CreateElement method on it, and passing the desired element as an argument inside quotation marks.
We can add text to the subheading the same way we did to the heading.
We can not only add text but also add any tags to it. Let’s say we want to assign a class to the subheading. We do that by using the .classList property which returns the class name and then calling add method on it using dot notation.
Appending it
If we inspect our page, we will see that the newly created tag was not added to our page. That is because whenever you create a new element, you have to append it.
Now, if you check the page again, the subheading has been added with the class name and the text that we defined.
Now you know how to create and make changes to the DOM. Stay tuned for my next blog where we go more in-depth about the types of methods that we can use with DOM.