DOM Manipulation in JavaScript

The Document Object Model (DOM) is a programming interface that represents the structure of a document as a tree of objects. Each node in the tree corresponds to an element in the document, and JavaScript can be used to manipulate these nodes, altering the content and structure of the HTML document.

Selecting Elements:

// Selecting elements by ID
const elementById = document.getElementById("myElementId");

// Selecting elements by class name
const elementsByClass = document.getElementsByClassName("myClassName");

// Selecting elements by tag name
const elementsByTag = document.getElementsByTagName("div");

// Selecting elements by CSS selector
const elementBySelector = document.querySelector("#myContainer .myClass");
const elementsBySelectorAll = document.querySelectorAll(".myClass");

Modifying Elements:

// Modifying text content
elementById.textContent = "New Text Content";

// Modifying HTML content
elementById.innerHTML = "<strong>New HTML Content</strong>";

// Changing attributes
elementById.setAttribute("src", "new-image.jpg");

// Modifying CSS styles = "red"; = "16px";

Creating and Appending Elements:

// Creating new elements
const newElement = document.createElement("div");

// Appending elements

// Removing elements

Event Handling:

// Adding event listeners
elementById.addEventListener("click", () => {
  console.log("Element clicked!");

// Removing event listeners
const clickHandler = () => {
  console.log("Element clicked!");

elementById.addEventListener("click", clickHandler);
elementById.removeEventListener("click", clickHandler);

Manipulating Classes:

// Adding and removing classes

// Toggling classes


DOM Manipulation is a fundamental skill in web development, allowing you to create dynamic and interactive web pages. By selecting and manipulating elements, you can respond to user interactions, update content, and create a seamless user experience.

Leave a Reply

Your email address will not be published. Required fields are marked *


Tag Cloud

.net algorithms angular api Array arrays async asynchronous basic-concepts big o blazor c# code components containers control-structures csharp data structures data types dictionaries docker dom dotnet encapsulation framework functions git guide javascript json leetcode linq lists loops methods MVC npm object oriented programming oop operators promisses sorted typescript variables web framework