DOM Manipulation In JavaScript

 DOM Manipulation, or Document Object Model Manipulation, refers to the process of dynamically interacting with the HTML and CSS of a web page using JavaScript. The DOM represents the structure of an HTML document as a tree-like data structure, where each node represents an element, attribute, or piece of text.

Here's an overview of how DOM manipulation works in JavaScript:

  1. Accessing Elements: You can access HTML elements in the DOM using methods like document.getElementById(), document.getElementsByClassName(), document.getElementsByTagName(), document.querySelector(), and document.querySelectorAll().

    Example:


  2. // Get element by ID var element = document.getElementById("myElement"); // Get elements by class name var elements = document.getElementsByClassName("myClass"); // Get elements by tag name var elements = document.getElementsByTagName("div"); // Query selector var element = document.querySelector("#myElement"); // Query selector all var elements = document.querySelectorAll(".myClass");


Manipulating Element Content: You can change the content of HTML elements by modifying their innerHTML, innerText, or textContent properties.

Example:


// Change inner HTML element.innerHTML = "<p>New content</p>"; // Change text content element.textContent = "New text content";


Changing Element Attributes and Styles: You can modify attributes like class, id, src, href, etc., and styles using JavaScript.

Example:


// Change class element.className = "newClass"; // Add class element.classList.add("newClass"); // Remove class element.classList.remove("oldClass"); // Toggle class element.classList.toggle("active"); // Change style element.style.backgroundColor = "blue";


Creating and Removing Elements: You can create new elements using document.createElement(), and append or remove them from the DOM using methods like appendChild(), removeChild(), insertBefore(), etc.

Example:


// Create a new element var newElement = document.createElement("div"); // Append element to another element parentElement.appendChild(newElement); // Remove element parentElement.removeChild(childElement);


Event Handling: You can attach event listeners to HTML elements to respond to user interactions like clicks, mouse movements, keypresses, etc.

Example:


// Add event listener element.addEventListener("click", function() { // Your code here });


By manipulating the DOM dynamically with JavaScript, you can create interactive and responsive web applications. However, it's important to use DOM manipulation judiciously to maintain code readability, performance, and accessibility.

Post a Comment

0 Comments