12 Best Dom Manipulation Methods in Javascript

What Is DOM?

DOM stands for Document Object Model (DOM). It is a programming interface for web documents(HTML and XML). DOM represents a logical structure for accessing and manipulating the document.

 With DOM programmers can easily navigate, modify, delete elements throughout the document. We can access, change, delete, or add anything in an HTML or XML document using the Document Object Model. The DOM can be used alongside any language.DOM represents the Whole Webpage in form of a tree.

Advantages and Disadvantages of Document Object Model 

Advantages Of DOM

1.You can do many things with DOM.

2. It is easily editable & customizable.

3.Using DOM We can change data on any HTML page without refreshing the page.

4.DOM makes it easy to navigate different elements.

Disadvantages Of DOM

1.As it is represented by a tree, it requires more memory.

2. Sometimes it can be hard to navigate elements.

Different Parts W3C(World Wide Web Consortium) DOM Standard

HTML DOM: It is a standard model for HTML-type documents.

XML DOM: It is a standard model for XML-type documents.

Core DOM: It is a standard model for all document types.

DOM defines the following –

HTML elements as ObjectsProperties of all HTML elements,events for All HTML elements,methods to access all HTML elements.

What is DOM Manipulation in Javascript?

While DOM is closely related to JavaScript, DOM is not a part of JS. It is not a programming language but a Web API used to build websites. As discussed DOM represents the Whole Webpage in form of a tree. To manipulate elements of the tree or Webpage we use JavaScript.

With the Document Object Model, Js can change the following – 

  • All the HTML elements on the web page
  • All the HTML attributes on the web page
  • All the CSS styles on the web page

You can also create new HTML events or react to all existing events on the webpage.  

Dom Manipulation Methods in Javascript

DOM is an object-oriented representation of the web page that can be manipulated by javascript or Jquery. Here I’m going to show some of the most commonly used DOM Manipulation Methods in Javascript for Web Developers.

Prerequisites: Basic understanding of Web and HTML,CSS,JS (Including Objects).

Objective: To understand or get familiar with the core DOM APIs and DOM manipulations method.

Best Dom Manipulation Methods in Javascript
Image Source : Unsplash
1.querySelector() 2. querySelectorAll() 3.createElement() 4.addEventListener()
5.removeEventListener() 6.appendChild() 7.replaceChild() 8.removeChild()
9.setAttribute() 10.getAttribute() 11.removeAttribute() 12.getComputedStyle()

1.querySelector()

querySelector() method is one of the most used DOM manipulation methods in javascript. querySelector is used to select elements. It returns the first element that matches a particular CSS selector.

Example: 

Best Dom Manipulation Methods in Javascript
<!DOCTYPE html>
<html>
<body>
<h2 class="element">Demo heading with class="element"</h2>
<script>
function demoFunction() {
  document.querySelector(".element").style.backgroundColor = "royalblue";
}
 demoFunction();
</script>
</body> 
</html>

Here, we are selecting an H2 with the class “element” and making the H2’s background color – red.

2. querySelectorAll()

querySelectorAll() method is similar to the querySelector() method, Instead of returning the first element that matches a particular CSS selector, It returns all or an array of Elements (a.k.a static NodeList object) with the same CSS selector.

Example : 

What is DOM Manipulation in Javascript?
<!DOCTYPE html>
<html>
<body>

<h1 class="Demo2">A heading with class="Demo2"</h1>
<h2 class="Demo2">A paragraph with class="Demo2".</h2> 

<script>
function Demo2_All() {
  let x, i;
  x = document.querySelectorAll(".Demo2");
  for (i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = "#27ae60";
     x[i].style.color ="#fff";
      x[i].style.padding="20px";
     
  }
}
 Demo2_All();
</script>

</body>
</html>

Here, we are selecting an array of elements(H1, H2) with the class “Demo2” and making their background-color – #27ae60, color – #fff, padding – 20px.

3.createElement()

The createElement() method enables us to create HTML element specified by tagName. It is a useful Dom Manipulation Method in Javascript.

Example : 

What is DOM Manipulation in Javascript?
<!DOCTYPE html>
<html>
<body>

<h3>Creating A Button using createElement </h3>
<script>
(function demo() {
  let btn = document.createElement("BUTTON");
  btn.innerHTML = "Button"; 
  document.body.appendChild(btn);
})();
</script>

</body>

Here, we are creating a button by using the createElement method.

Also Read:What is Redis Database? – Remote Dictionary Server

4.addEventListener()

The addEventListener is a Dom Manipulation Method in JS that enables us to add any event to the document or HTML. This method attaches or adds an event handler to a particular element. This method is a must to learn DOM manipulation in Javascript properly.

Example : 

Dom Manipulation Methods in Javascript
<!DOCTYPE html>
<html>
<body>
<style>
#event-ele{color:#27ae60; font-size:40px;font-weight:600;}
#demo-btn{background:#333;outline:none; color:#fff;padding:10px 30px;border:none;}
</style>

<h2>addEventListener() Example using a button</h2>

<button id="demo-btn">Click Here</button>


<h3 id="event-ele"></h3>

<script>
document.getElementById("demo-btn").addEventListener("click", function() {
  document.getElementById("event-ele").innerHTML = "Qualified Geek";
});
</script>

</body>
</html>

Here we are adding an onclick event to the button with the ID (demo-btn). Using that onclick event, we are printing some text.

5.removeEventListener()

Just like the addEventListener, removeEventListener removes the attached event of any specific element. 

Example : 

Dom Manipulation Methods in Javascript
<!DOCTYPE html>
<html>
<body>
<style>
#event-ele{color:#27ae60; font-size:40px;font-weight:600;}
#demo-btn , #demo-btn2{background:#333;outline:none; color:#fff;padding:10px 30px;border:none;}
</style>

<h2>removeEventListener() Example using a button</h2>

<button id="demo-btn">Click Here</button>
<button id="demo-btn2" onclick="removeEvent()">Remove Event</button>


<h3 id="event-ele"></h3>

<script>
document.getElementById("demo-btn").addEventListener("dblclick", addEvent);

function addEvent() {
  document.getElementById("event-ele").innerHTML = Math.random();
}

function removeEvent() {
  document.getElementById("demo-btn").removeEventListener("dblclick", addEvent);
}

</script>

</body>
</html>

Here We have two buttons 1.for the double click event and 2. for removing the event.

6.appendChild()

To append or add a node as the last of a node, we use appendChild 

appends a node as the last child of a node. We can dynamically add an element to DOM. 

Example :

Manipulation Methods in Javascript
<!DOCTYPE html>
<html>
<body>
<style>

.demo-btn{background:#27ae60;outline:none; color:#fff;padding:10px 30px;border:none;}
#h3{
padding:30px 30px 30px 0px;
font-size:40px;

}
</style>

<h2>The AppendChild Method </h2>
<div id="h3" > </div>

<button class="demo-btn" onclick="addingElement()">Click Here</button>

<script>
function addingElement() {
  let h3 = document.createElement("H3");
  let childNode = document.createTextNode("Hello Geeks");
  h3.appendChild(childNode);
  document.getElementById("h3").appendChild(childNode);
}
</script>

</body>
</html>

Here we are adding an element after the h2 using the appendChild() method.

7.replaceChild()

Now you have added a new node using the appendChild method. But how do you replace it? Using the replaceChild() method, you can easily replace a child node with a new node.

Example:

Dom Manipulation Methods in Javascript

<!DOCTYPE html>
<html>
<body>
<h3>replaceChild() </h3>
<ul id="demoList"><li>Wordpress</li><li>HTML</li><li>Javascript</li><li>Jquery</li></ul>

<button onclick="myFunction()">Click Here</button>
<script>
function myFunction() {
  var textnode = document.createTextNode("Reactjs");
  var item = document.getElementById("demoList").childNodes[0];
  item.replaceChild(textnode, item.childNodes[0]);
}
</script>

</body>
</html>

Here we are replacing the first item of the list “WordPress” with “ReactJS”.

8.removeChild()

Just like the replaceChild() method, removeChild() is used to remove a particular child node of an Element.

Example: 

Advantages and Disadvantages of Document Object Model (DOM)
<!DOCTYPE html>
<html>
<body>
<h3>replaceChild() </h3>
<ul id="demoList"><li>NextJs</li><li>SASS</li><li>Node</li><li>Mongo</li></ul>

<button onclick="remove()">Click Here</button>


<script>
function remove() {
 
 let demoItem = document.getElementById("demoList");
  demoItem.removeChild(demoItem.childNodes[0]);
}
</script>

</body>
</html>

Here we are removing the first item of the list “NextJs“.

Also Read: 20 Best Visual Studio Code Extensions for Web Development

9.setAttribute()

setAttribute() is one of those convenient Dom Manipulation Methods in Javascript. You can easily add the specified attribute to an element.

Example:

Advantages and Disadvantages of Document Object Model
<!DOCTYPE html>
<html>
<head>
<style>
.demo1 {
  color:#27ae60;
}
</style>
</head>
<body>

<h1>setAttribute() Method in Javascript</h1>

<h2> Qualified Geek </h2>

<button onclick="settingAttribute()">Try it</button>

<script>
function settingAttribute() {
  document.getElementsByTagName("H2")[0].setAttribute("class", "demo1"); 
}
</script>

</body>
</html>

Here, we are creating a class named “demo1“. We are also changing the color of that H2 using the setAttribute() method.

Also Read:10 Best NPM Packages for Beginners in 2021

10.getAttribute()

Similar to setAttribute, the getAttribute() method returns the value of the attribute of a specific element.

Example:

What is DOM Manipulation in Javascript?

<!DOCTYPE html>
<html>
<head>
<style>
#event-ele{color:#27ae60; font-size:40px;font-weight:600;}
#demo-btn {background:#333;outline:none; color:#fff;padding:10px 30px;border:none;}
</style>
</head>
<body>

<h1 id="event-ele" class="democlass">getAttribute In JS</h1>
<button id="demo-btn" onclick="myFunction()">Click Here</button>
<p id="demo" style="color:#27ae76; font-size:32px;font-weight:400;"></p>

<script>
function myFunction() {
  let x = document.getElementsByTagName("H1")[0].getAttribute("id"); 
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

Here we are getting the attribute or id of the h1.

11.removeAttribute()

As the name suggests, RemoveAttribute is a method that we can use to remove the specified attribute from an element. 

Example:

Dom Manipulation Methods in Javascript
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
  color: #fff;
  Background:#27ae60;
  width:40%;
  padding:30px;
  text-align:center;
  
}
</style>
</head>
<body>

<h1 class="demo">Geeks</h1>
<button onclick="remove()">Click Here</button>

<script>
function remove() {
  document.getElementsByTagName("H1")[0].removeAttribute("class"); 
}
</script>

</body>
</html>

Here we are removing the class named “demo“.

12.getComputedStyle()

getComputedStyle() or window.getComputedStyle() method returns an object containing all the actual CSS properties and values of a particular element. It is one of the best Dom Manipulation Methods in Javascript.

Example:

What is DOM Manipulation in Javascript?
<!DOCTYPE html>
<html>
<body>
<style> 
#styling1{
display:flex;
justify-content:center;
align-items:center;
height:50px;
background:#2980b9;
color:#fff;
}

</style>
<h2 id="styling1">Test Div</h2>
<h3>color: <span id="demo"></span> or (#fff)</h3>

<script>
(function myFunction(){
  var elem = document.getElementById("styling1");
  var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("color");
  document.getElementById("demo").innerHTML = theCSSprop;
})();
</script>

</body>
</html>

Here we are getting the color of the id with the name “styling1”.

Can We Create a Website Without DOM?

It depends on how you see it. If you don’t know anything about DOM, then you might think that the webpage is made of HTML only. It is because DOM is a logical representation of the Web Page. It is denoted by a tree with the HTML element at the top, then the head and body elements, and other smaller elements (paragraph, Heading, etc.).The browser understands the DOM structure of any Webpage. Creating a website without DOM is Impossible. It will be something similar to a live website without hosting or a database (Just because you cannot see it doesn’t mean it is not there).

Is it necessary to know the DOM with JS?

Although it is not compulsory to learn DOM with JS, You have to learn it at some point if you’re a web dev or something. I would highly recommend you to learn DOM.DOM is not that difficult to understand. 

Leave a Comment