Young african male programmer writing program code sitting at the workplace with three monitors in the office. Image focused on the screen

What is DOM Manipulation in JavaScript?

DOM or Data Object Model is a tree representation of an HTML page. DOM manipulation means changing text, color, styles and dimensions of any element on the page to create better user experience and accomplish meaningful tasks. If we print document objects in our console we will observe many methods and properties associated with that. Those properties and methods actually model or represent different functionalities which we can perform using them in JavaScript. 

 

 

 

 

 

First of all we need to make an index.html file and place this code in there.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
  	<title>Item Lister</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
	<header id="main-header" class="bg-success text-white p-4 mb-3">
    <div class="container" id="container">
      <div class="row">
        <div class="col-md-6">
            <h1 id="header-title">Item Lister</h1>
        </div>
        <div class="col-md-6 align-self-center">
            <input type="text" class="form-control" id="filter" placeholder="Search Items...">
        </div>
      </div>
    </div>
  </header>
  <div class="container">
   <div id="main" class="card card-body">
    <h2 class="title">Add Items</h2>
    <form id="addForm" class="form-inline mb-3">
      <input type="text" class="form-control mr-2" id="item">
      <input type="submit" class="btn btn-dark" value="Submit">
    </form>
    <h2 class="title">Items</h2>
    <ul id="items" class="list-group">
      <li class="list-group-item">Item 1 <button class="btn btn-danger btn-sm float-right delete">X</button></li>
      <li class="list-group-item">Item 2 <button class="btn btn-danger btn-sm float-right delete">X</button></li>
      <li class="list-group-item">Item 3 <button class="btn btn-danger btn-sm float-right delete">X</button></li>
      <li class="list-group-item">Item 4 <button class="btn btn-danger btn-sm float-right delete">X</button></li>
    </ul>
   </div>
  </div>
  
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="dom/dom.js"></script>
</body>
</html>

Now I am just using jQuery to use bootstrap. It will make our page look good and it will serve no purpose in DOM manipulation. That I will do entirely using JavaScript. And then in order to use a few methods which are provided by document object we can run this code.

console.log(document);
console.log(document.domain);
console.log(document.URL);
console.log(document.title);
document.title = "change the title";
console.log(document.doctype);
console.log(document.head);
console.log(document.body);
console.log(document.all);
console.log(document.forms);
console.log(document.links);
console.log(document.images);

Now there are a few ways to select elements.

let headerTitle = document.getElementById('header-title');

And we can also select elements on the basis of class and it will return us an HTML collection and we have to loop through to get our results. Like here we are changing the background of list items. 

let list_items = document.getElementsByClassName('list-group-item');

 for(let i=0; i<list_items.length; i++){
 	list_items[i].style.backgroundColor = 'grey';
 }

Another way to select elements is by a tag name. 

let items = document.getElementsByTagName('li');

 items[1].innerText = 'Hello 2';
 items[1].style.fontWeight = 'bold';
 items[1].style.backgroundColor = 'Yellow';

 for(let i=0; i<items.length; i++){
 	items[i].style.backgroundColor = 'grey';
 }

It will also give us an HTML collection which we have to traverse and manipulate using a for loop. 

We can select elements using the query selector. This allows us to select elements by ID, tagname, class name or even by type. 

 let header = document.querySelector('#main-header');
 header.style.borderBottom = 'solid 4px black';

 let input = document.querySelector('input');
 input.value = "hello world";

 let submit = document.querySelector('input[type="submit"]');
 submit.value = 'SEND';

 let list_item = document.querySelector('.list-group-item');
 list_item.style.color = 'red';

We can select elements like CSS selectors using a query selector.

let lastItem = document.querySelector('.list-group-item:last-child');
 lastItem.style.color = 'blue';

 let thirdItem = document.querySelector('.list-group-item:nth-child(3)');
 thirdItem.style.color = 'red';

 let odd = document.querySelectorAll('li:nth-child(even)');
 let even = document.querySelectorAll('li:nth-child(odd)');


 for(let i=0; i<odd.length; i++){
 	odd[i].style.backgroundColor = 'grey';
 	even[i].style.backgroundColor = '#ccc';
 }
We can also select parent elements and childrens.
 let itemsList = document.querySelector('#items');
 console.log(itemsList.parentElement);
 console.log(itemsList.parentElement.parentElement.parentElement);

let itemList = document.querySelector('#items');
 itemList.children[1].style.backgroundColor = 'grey';
 itemList.firstElementChild.innerText = "Hello 1";


 console.log(itemList.lastElementChild);
 itemList.lastElementChild.innerText = "Hello 4";

 console.log(itemList.nextElementSibling);

 console.log(itemList.previousElementSibling);
 itemList.previousElementSibling.style.backgroundColor = 'Yellow';

Now using our knowledge we can create a full CRUD application with filters. 

 let form = document.getElementById('addForm');
 let itemList = document.getElementById('items');
 let item = document.getElementById('item');
 let filter = document.querySelector('input[type="text"]');


 form.addEventListener('submit', addItem);
 itemList.addEventListener('click', deleteItem);
 filter.addEventListener('keyup', applyFilter);

 function addItem(e){
 	e.preventDefault();
 	let itemToAdd = item.value;
    
     if(itemToAdd != ''){
         let itemText = document.createTextNode(itemToAdd);
         let deleteButtonCross = document.createTextNode('X');
         let space = document.createTextNode(' ');

         let itemLi = document.createElement('li');
         itemLi.className = 'list-group-item';

         let itemDeleteButton = document.createElement('button');
         itemDeleteButton.className = 'btn btn-danger btn-sm float-right delete';
         itemDeleteButton.appendChild(deleteButtonCross);

         itemLi.appendChild(itemText);
         itemLi.appendChild(space);
         itemLi.appendChild(itemDeleteButton);   

         itemList.appendChild(itemLi);
     }
     else{
         alert('Please add some item first');
     }
 }


 function deleteItem(e){
    
     if(e.target.classList.contains('delete')){
         let btn = e.target;
         let li = btn.parentElement;
         itemList.removeChild(li);
     }
 }

 function applyFilter(e){
     let filterText = e.target.value.toLowerCase();
    
     let items = document.getElementsByTagName('li');
    
     Array.from(items).forEach(function(item){
       
         let itemName = item.firstChild.textContent;
        
         if(itemName.toLowerCase().indexOf(filterText) != -1){
             item.style.display = 'block';
         }
         else{
             item.style.display = 'none';
         }
        
     });
 }