DEV Community

Cover image for 7 Javascript Methods That Aid DOM Manipulation
deji adesoga
deji adesoga

Posted on • Edited on

7 Javascript Methods That Aid DOM Manipulation

There are no beautiful surfaces without a terrible depth.
-Friedrich Nietzsche

Introduction

The HTML Document Object Model(DOM) is the owner of all other object in the web page.There are so many ways javascript methods that can be used to manipulate the DOM.

In this tutorial, we will be looking at just 7 of those javascript methods to carryout DOM manipulation. Lets get started!

1. document.createElement()

The createElement() method creates a new HTML element specified by the tagname.

Methods To Be Used In the Code Example

createTextNode() --- Helps us to create a new text node

getElementById() --- Helps Us to access an element with a specific ID

appendChild() ---Adds an element as the last child of the document body

replaceChild() --- Replaces a child node within the parent node

Code Example

Result

Hello World
This is a new text paragraph.

Summary

We have a div element that contains a p tag and an h2 tag. After which we got their id's with the document.getElementById() method.

Then we declared two variables. The first one creates a p tag using the createElement() method , while the second one creates a new text using the createTextNode() method.

Finally, we called the appendChild() method and the replaceChild() method to create a new text paragraph.

2. Node.appendChild()

The appendChild() method like we said earlier creates a new element and adds it to the parent node. It is important to note that the appendChild() method adds the new element at the end of any other children of a specified parent node.

Methods To Be Used In the Code Example

querySelector() --- Helps us to target the element in the DOM

createElement() --- Helps us to create a new HTML element in the DOM

textContent ---Helps us to set a given text to the Node

Code Example

Result

I am number one
I am number two
I am number three
I am number four

Summary

We have a list in our HTML which are just three in number. In our script tag we were able to add a fourth member to the list. First we selected the ul tag and then created a new li tag with the createElement() method.

Next we added some content to the newly created list, before appending it to the list. Notice that the newly created list is added at the bottom of the page.

3. Node.insertBefore()

This method inserts a node before the reference node as a child of a specified parent node. That is, it adds a specific child element before another child element.

Methods To Be Used In the Code Example

querySelector() --- Helps us to target the element in the DOM

createElement() --- Helps us to create a new HTML element in the DOM

textContent ---Helps us to set a given text to the Node

Code Example

Result

I am the new number one
I am number one
I am number two
I am number three

Summary

The insertBefore() element adds the newly created li tag to the top. In our script tag, we had to make a reference to the parent element or the new li tag would not have been created.

Here is the format we used: parentNode.insertBefore(newNode, referenceNode);

parentNode : The parent of the newly inserted node.
newNode The: node to be inserted.
referenceNode: The node before which newNode is inserted.

4. Node.removeChild()

The removeChild() method removes a child node from the DOM and returns the removed node. Note that the removed child node still exists in memory, but is no longer part of the DOM.

Methods To Be Used In the Code Example

querySelector() --- Helps us to target the element in the DOM

Code Example

Result

Second on the list
third on the list

Summary

After using the querySelector() method to select both the parent and child elements in our script tag, then we called the removeChild() method. By default, this removes the first item on the list.

5. Node.replaceChild()

The replaceChild() method replaces a child node within the given parent node. This method accepts two parameters: the node to be inserted and the node to be replaced. It follows this format: parentNode.replaceChild(newChild, oldChild);

Methods To Be Used In the Code Example

querySelector() --- Helps us to target the element in the DOM

createElement() --- Helps us to create a new HTML element in the DOM

textContent ---Helps us to set a given text to the Node

Code Example

Result

This Is the new first Paragraph
This is the Second Paragraph
This is the Third Paragraph

Summary

In the script tag, we selected both the parent element ul and the child element li. Then we created a new li tag.

After which we assigned the newly created li tag a new content using textContent.

We then called the replaceChild() method, which replaced the first item on the list with the new liitem we created.

6. Element.setAttribute()

The setAttribute() method takes in two parameters: Element.setAttribute(name, value);

This method either adds a new attribute to the DOM element, or updates the values of an attribute that already exists.

Methods To Be Used In the Code Example

querySelector() --- Helps us to target the element in the DOM

Code Example

Result

List Editable
Old Name

Summary

In our script tag, we selected the li tag using the querySelector() method.

We then called the setAttribute() method. The first parameter we called makes the first item on the list to be editable when clicked upon, making it possible for us to change the text of the first item on the fly, directly from the web page.

7. Element.getAttribute()

The getAttribute() method of the element interface returns the value of a specified attribute on a DOM element. If the specific value does not exist, the value returned will either be null or an empty string "".

It takes the following format: element.getAttribute(attributeName);

Methods To Be Used In the Code Example

querySelector() --- Helps us to target the element in the DOM

document.write() --- Helps us to write a string of text to the DOM

Code Example

Result

https://dev.to/

Summary

In our script tag, we selected the a tag. Next up, we used the getAttribute() method to select the href attribute inside the a tag.

Finally we displayed the full URL of the href attribute in the DOM by using the document.write() method.

Conclusion

One of the most useful capabilities of javascript is its ability to manipulate the DOM. It is one of the skills you need to master if you want to improve your javascript abilities as a web developer.

In this tutorial we were able to cover a few of them. So you can go ahead and make further research so as to strengthen your knowledge base about DOM manipulation with javascript.

To get more free content on web development, subscribe to my newsletter:
here

Top comments (24)

Collapse
 
nickytonline profile image
Nick Taylor

Always good to demonstrate some of the basics. Another good one is HTMLElement.dataset, which allows you to access/set data-* attributes. Looking forward to your next post Deji!

Collapse
 
desoga profile image
deji adesoga • Edited

Thanks Nick, I appreciate your response. The foundation is very important. I wasn't aware about HTMLElement.dataset, i'll take a good look at it.

Collapse
 
kysuga profile image
Kyle Masuga

Deji, I just wanted to give a shout out to you and thank you for writing this post.

I came across it by chance, after reading through @fossheim's article on how she recreated a Polaroid camera with CSS (also amazing) and saw the link to your post in the footer. Your post had exactly the answer I was looking for, for my project, which was #4, so thank you!

Collapse
 
odddev profile image
Kai • Edited

Just a quick hint. Every DOM ID is available as a global variable out of the box.

Don't use that in actual code obviously. Just for show-casing/fiddling.

Collapse
 
lexlohr profile image
Alex Lohr

Yes, but only as long as no script overwrites the global reference.

<div id="oneId"></div>
// evil js
oneId = 'haha!';

console.log(oneId);
Collapse
 
odddev profile image
Kai

That comment is so ridiculous, you can even post it as a general reply to any JS code-including article.

What's the point?

Thread Thread
 
lexlohr profile image
Alex Lohr • Edited

The point here is that you probably shouldn't rely on global variables and better use the DOM methods. It is also much more probable that your IDs are overwritten by another script accidentially than DOM methods.

Thread Thread
 
odddev profile image
Kai • Edited

That's absolutely true! Never use that for actual productive code.
Just a quick tip for fiddling purposes.

Edit: Added this to my initial comment

Collapse
 
drozerah profile image
Drozerah • Edited

I have recently discovered the Element​.get​Bounding​Client​Rect() , the method give the left, top, right, bottom, x, y, width, and height of DOM element :

function myFunction() {
  var div = document.getElementById("myDiv");
  var rect = div.getBoundingClientRect();
  x = rect.left;
  y = rect.top;
  w = rect.width;
  h = rect.height;
  alert ("Left: " + x + ", Top: " + y + ", Width: " + w + ", Height: " + h);
}


`
pretty neat ! isn't it ?

Collapse
 
desoga profile image
deji adesoga

Yes it is and good find too.

Collapse
 
kdraypole profile image
Kobe Raypole

Great article! Just curious, do you have any thoughts on using plain old javascript for DOM manipulation over something like jQuery?

I've always preferred jQuery as it offers browser compatibility, simplified operations, and lots of cool features. But I have met developers who prefer to do it the "old fashion way".

Collapse
 
desoga profile image
deji adesoga • Edited

Thanks a lot Kobe. When it comes to DOM manipulation, I prefer using old javascript. However, it all depends on the size of the application.

If it's an application that has the potential to scale over time, then I would want to use a framework like Angular 6 or jQuery just like you've said, so as to avoid some complications over time.

The "old fashion way" could lead to a world complexity in terms of code-maintenance in the long run.

Collapse
 
gypsydave5 profile image
David Wickes

Ahaha - that Nietzsche quote - the DOM as a Dionysian abyss. That gave me a laugh.

Just a quick one on language - in the title it should be 'Aid' not 'Aids'.

Collapse
 
desoga profile image
deji adesoga

Glad you enjoyed it. And yes, I've changed the title. Thanks for pointing that out.

Collapse
 
muescha profile image
Michael

the slug is still the old title with s

Collapse
 
lexlohr profile image
Alex Lohr

Nice summary. I'm only missing .insertBefore(newChild, referenceElement) and the child-/sibling-/parentNode reference properties in this list.

Collapse
 
desoga profile image
deji adesoga

Maybe I'll add that in part 2.

Collapse
 
motilola profile image
Ola

Thanks Deji. A couple of things became clearer to me after reading this. Saved to be read again and again :)

Collapse
 
desoga profile image
deji adesoga

Glad to know It was of help to you.

Collapse
 
ygorbunkov profile image
ygorbunkov • Edited

How come there's no place for insertAdjacentHTML() in this article?

Collapse
 
lexlohr profile image
Alex Lohr

Because it is a security problem, very much like .innerHTML, when you use it to add arbitrary HTML.

Collapse
 
rafyramy94 profile image
Rafy Ramy

This is awesome, thanks for sharing 😊