Basic DOM Manipulation in JavaScript


We are all familiar with JavaScript. This article is for those who have not touched JavaScript yet. Here I will tell you how to do simple DOM manipulations in JavaScript. 
If you want to create a new element in the DOM, you can do as follows:
  1. Var myDiv = document.createElement('div');   
If you want to add a new element to the existing element, you can do as follows.
  1. document.body.appendChild(div);   
Here I am appending a div to the body.
Style manipulation
If you want to add some styles to an existing element, you can do as follows.
  1. = '142px';     
  2. = '26px';  
Modification  Using classes
If you want to assign a class name to an existing element, you can do as follows:
  1. div.className = 'myClassName';  
Using ID
  1. = 'myID';  
Change the contents using HTML
  1. div.innerHTML = '<div class="myClassName">This is my HTML</div>';  
using text
  1. div.textContent = 'This is my text';  
To remove an element from the DOM:
  1. div.parentNode.removeChild(div);  
Here we are removing a div from the parent node.
We can access the elements in several ways. Let us see that now.
  1. document.getElementById('myID');  
  1. document.getElementsByTagName('p');  
  1. document.getElementsByClassName('myClassName');  
CSS selector
  1. document.querySelector('div #myID .myClassName');  
That's all.
I hope someone finds this useful. Thanks for reading.
Kindest Regards,