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:
- Var myDiv = document.createElement('div');
Addition
If you want to add a new element to the existing element, you can do as follows.
- 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
- div.style.right = '142px';
- div.style.left = '26px';
Modification
Using classes:
If you want to assign a class name to an existing element, you can do as follows:
- div.className = 'myClassName';
Using ID:
Change the contents
using HTML:
- div.innerHTML = '<div class="myClassName">This is my HTML</div>';
using text:
- div.textContent = 'This is my text';
Removal
To remove an element from the DOM:
- 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
- document.getElementById('myID');
Tags
- document.getElementsByTagName('p');
Class
- document.getElementsByClassName('myClassName');
CSS selector
- document.querySelector('div #myID .myClassName');
That's all.
I hope someone finds this useful. Thanks for reading.
Kindest Regards,
Sibeesh