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 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 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 new elements
const newElement = document.createElement("div");
// Appending elements
elementById.appendChild(newElement);
// Removing elements
elementById.removeChild(newElement);
// 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);
// Adding and removing classes
elementById.classList.add("newClass");
elementById.classList.remove("oldClass");
// Toggling classes
elementById.classList.toggle("active");
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.
Encapsulation and abstraction are two pillars of object-oriented programming (OOP) that play a vital role…
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects to take on…
Inheritance is a cornerstone of object-oriented programming (OOP) and one of its most powerful features.…
In the world of C# and object-oriented programming (OOP), classes and objects form the backbone…
In modern C# programming, working with data collections is a common task. Understanding how to…
Exception handling is a critical part of writing robust and maintainable C# applications. It allows…