Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

DOM Manipulation

DOM Manipulation

DOM (Document Object Model) manipulation is a fundamental aspect of web development. It allows you to interact with and modify the structure and content of a web page dynamically. Here's an introduction to DOM manipulation in JavaScript:

Accessing DOM Elements:

You can access DOM elements using JavaScript. There are several methods available:

By ID:

let elementById = document.getElementById('myElementId');
 

By Class Name:

let elementsByClass = document.getElementsByClassName('myClassName');
 

By Tag Name: 

let elementsByTag = document.getElementsByTagName('div');
 

By CSS Selector:

let elementBySelector = document.querySelector('.mySelector');
let elementsBySelectorAll = document.querySelectorAll('.mySelector');
 

Modifying Element Properties:

You can change various properties of DOM elements:

Changing Content:

elementById.innerHTML = 'New Content'; // Set HTML content
elementById.textContent = 'New Content'; // Set text content
 

Changing Styles:

elementById.style.color = 'red';
elementById.style.fontSize = '20px';
 

Adding/Removing Classes:

elementById.classList.add('newClass');
elementById.classList.remove('oldClass');
 

Creating and Appending Elements:

You can create new elements and append them to the DOM:

let newElement = document.createElement('div'); // Create a new 
element newElement.textContent = 'New Element'; // Set content newElement.classList.add('newClass'); // Add class document.body.appendChild(newElement); // Append to the body
 

Event Handling:

You can attach event listeners to DOM elements to respond to user interactions:

elementById.addEventListener('click', function() {
  alert('Element clicked!');
});
 

Traversing the DOM:

You can navigate the DOM tree to access different elements:

let parentElement = elementById.parentNode; // Access parent element
let firstChildElement = parentElement.firstChild; // Access first child element
let nextSiblingElement = elementById.nextElementSibling; // Access next sibling element

 

Removing Elements:

You can remove elements from the DOM:

let elementToRemove = document.getElementById('elementToRemove');
elementToRemove.parentNode.removeChild(elementToRemove);
 

Manipulating Forms:

You can interact with form elements:

let inputElement = document.getElementById('textInput');
let inputValue = inputElement.value; // Get input value

let checkboxElement = document.getElementById('checkbox');
let isChecked = checkboxElement.checked; // Check if checkbox is checked