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
elementById.style.color = "red";
elementById.style.fontSize = "16px";

Creating and Appending Elements:

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

// Appending elements
elementById.appendChild(newElement);

// Removing elements
elementById.removeChild(newElement);

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
elementById.classList.add("newClass");
elementById.classList.remove("oldClass");

// Toggling classes
elementById.classList.toggle("active");

Conclusion:

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 *


Categories


Tag Cloud

.net addEventListener 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 framework functions git guide javascript json leetcode loops methods MVC node.js npm object oriented programming oop operators promisses server-side sorted typescript variables web framework