Basic DOM Manipulation in JavaScript

Introduction

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.

Creation

If you want to create a new element in the DOM, you can do as follows:

  1. Var myDiv = document.createElement('div');  
Addition

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.

Positioning
  1. div.style.right = '142px';   
  2. div.style.left = '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. div.id = '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';  
Removal

To remove an element from the DOM:
  1. div.parentNode.removeChild(div);  
Here we are removing a div from the parent node.

Accessing

We can access the elements in several ways. Let us see that now.

ID
  1. document.getElementById('myID');  
Tags
  1. document.getElementsByTagName('p');  
Class
  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,

Sibeesh

Up Next
    Ebook Download
    View all
    Learn
    View all