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