There are about a million different ways to manipulate the DOM. Most people that are new to javaScript see a lot of DOM manipulation processes that the don't
have an idea of what is going on. There is no text explaining to them what is actually going on and how it is linked to the template. I want to
use this write up to cover a few techniques to manipulate the DOM.
To get started, let us create a blank html file that links to a script file.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Dom manipulation</title>
<script src="script.js">
</script>
</head>
<body>
</body>
</html>
Adding elements to the page
The first thing we are going to do is add an element to the page . This is pretty simple. On the script.js file add
const body = document.body
This is a variable set to the body . We can append elements to the body. We can do this by using the append() method
body.append()
We can also say
body.appendChild();
The append method appends to a body and the appendChild method also does the same thing. They are almost identical methods but they have a few difference. The major difference is that in the append() method we can actually append a string
For example
body.append("Hello World");
The hello world will appear on the screen
//show screen here
But if the string is called in the appendChild method we get an error
body.appendChild("Hello World");
The appended string does not show on the screen. When we take a look at the console. We will see that the console throws an error which says the appendChild method failed to execute "node" parameter is not of type node and also not a string. But if we append an element to the appendChild method we will see it display. This shows that in the appendChild method only elements like divs, span, anchorTypes can be appended to it. While with the append method we can append all types of elements as well as strings. The append method has a little bit more of versatillity, it gives us the option of appending multiple strings, divs or any other elements at once.
What if elements are to be appended to a page instead of strings because generally we would want to be appending elements to our page instead of strings. How do we do this. It is actually very easy. With elements all we have to use is the document.createElement method. You just pass the type of element you want to create.
document.createElement('div');
The elements could be could be headings, headers, image, input, iframes. e.t.c. If we save the div element we created above, nothing is going to happen. This is because we created our element but we haven't actually added it to our page/ HTML. Creating something in javaScript and adding it are two different things. When we create something in javScript it is a reference to an element and we need to add the element to the page. To do that we can
const div = document.createElement('div');
body.append(div);
We created a variable div and appended the div to our page. We can add some text to the div by two ways.
div.innerText = "Hello World"
We have set it to the hello world string. We can now say
body.appendChild(div);
Hello world would still be printed on our screen.
Another way to to add text is to use
div.textContent = "Hello World"
It gives the exact same result. So what is the difference between the textContent and innerText methods. They look like they do the same thing. Text content prints all of the exact text content with spacing and indentation, while innnerText looks at the css to see if there are any properties it needs to implement before printing out.
If we want to render a HTML inside of a div of any element we use the innerHTML method
div.innerHTML = "<strong>hello world</strong>"
It implements the html on the component. This is a really powerful tool because it allows html to be rendered directly in javascript but it has a huge security problem. The problem being that if users of your code or application are allowed to put user generated content into an inner HTML, they can write malicious code which becomes a problem. The innerHTML is the only way an element can be added to a string for it to render. There is another way to do this though
const strong = document.createElement("strong");
strong.innerText = "Hello World";
div.append(strong);
When the above code is saved, we get the exact same result as when we used the innerHTML method. What we did is to just break it out and write it by hand. It is a much more secure way to do this..
The append method can be used on any element on the entire page, not just the body.
We have been talking about adding elements to our DOM. What if we want to remove items from the DOM. WE use the
const div = document.querySelector('div');
const spanH1 = document.querySelector('#h1');
const spanBye = document.querySelector('#by');
to select the element and then delete the element by
spanBye.remove();
The spanBy is the class of a span element. we use the id or class to identify the element we want to remove. The above method deletes the element from existance. We can re-add the element to the DOM by using the append(); method.
Another way we can remove an element is to remove it from the parent. We can use the method
div.removeChild(spanHi);
it will do exactly the same thing with the remove method we just used in the first example.
We have covered the methods of adding and removing elements from the DOM. What if we want to get properties of elements or just add classed. This is where most DOM manipulations are done.
There are tons of different tools that can be used to achieve this.
The first one we want to take a look at is a way to modify the attributes of an element. To execute this we can use the method
spanH1.getAttribute("id");
It fetches the attribute id of the above variable. We can ommit the getAttribute() method an d just go to the attribute directly by
spanH1.id
It still fetches the attribute. This is because if there is an attribute that can be gotten from an element using the etAttribute() method, that means it already exist on the element itself and can be accessed directly instead. Sometimes the attribute can not be gotten directly from the element. This is where the getAttribute() method becomes useful.
Another method we can use to manipulate the DOM is the setAttribute method.
spanH1.setAttribute('id', 'ABC');
It changes the value of the ekement. The first parameter is the the attribute to be changed. The second parameter is the value to change the attribute to. We can also set attributes by a simple
spanH1.id = 'abc'
To remove an attribute from the DOM we use the
spanH1.removeAttribute();
method. It is agreat way to remove attributes from a DOM element. To check all the data attributes in an element we can use th e dataSet method. It contains all of the attributes of an element. Let us log a dataSet() method to see what we are working on.
console.log( spanH1.dataSet);
If we go over to the console, we will see that we have a DomstringMap with our test property. This shows that with dataSet we can access any data property by just typing the property out and setting the properties to a dataSet method.
spanH1.dataSet.newName = 'All new Name '
If the element is grabbed and the attribute is looked at, we discover that it has changed.
The next thing we want to talk about is accessing the classes of an element which can be done using a classList() method. We can add a class to an element by
```
spanH1.classList.add('new-class');
```
When the above code is saved , a new class will be added to the element. A class can also be removed by
spanH1.classList.remove('new-class');
Save the above code and the class is removed. To toggle a class we can use. For example
```
spanH1.classList.toggle('new-class');
```
It removes a class that already exist or adds one if it does not. A boolean can be added to the toggle method. What it will do is it will automatically remove the class if we pass in false as the second argument or add a class if we pass in true.
```
spanH1.classList.toggle('new-class', false);
```
It is a great way to add or remove a class based on a boolean.
We have covered a few ways of manipulating the DOM. I hope to cover some few more in my next article. Looking forward to seeing you there. Cheers
Top comments (0)